PHP: Add new Record to MySQL in wordpress CMS-II

1. To save record in table in MySQL in wordpress ,first of all configure your “wp-config.php”

php6

Edit above file

define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', '');

/** MySQL hostname */
define('DB_HOST', '127.0.0.1');

2. Install plugin for PHP code execution

php_code

3. Activate the plugin and open to write PHP code

plug

4. Click on “PHP Code” & Add New PHP Code

insertphp

 Complete code is here

<?php
$mess="";
if(isset($_POST["submit"]))
{
    if(empty($_POST["roll"])or empty($_POST["nam"])or empty($_POST["course"]))
	{
	$mess= "field empty";	
	}	
	
	$r=$_POST["roll"];
	$n=$_POST["nam"];
	$c=$_POST["course"];
	
	$host="localhost";
	$user="root";
	$pass="";
	$dbname="wordpress";
	$db= new  mysqli($host,$user,$pass,$dbname);
	if ( ! $db->connect_error) 
	{
		$sql="insert into students(roll,name,course)values('$r','$n','$c')";
	   $result = $db->query($sql);
	 if( $result!=0)
	 {
		 $mess= "Inserted Sucessfully";
		 
	 }
	 else
	 {		 $mess= "......not Inserted ";
	 echo $result;	
	 }
}
else
{
echo 'The connection to the database could not be established.';
}
}
?>
<form action="/wordpress/hello-world/" method="POST">
<div style="width:600px; margin: auto;">
	<table>
		<tr>
			<td>
			ROLL	
			</td>
			<td>
			<input type="text" name="roll"/>	
			</td>
		</tr>
		<tr>
			<td>
			NAME	
			</td>
			<td>
			<input type="text" name="nam"/>	
			</td>
		</tr>
		<tr>
			<td>
			COURSE	
			</td>
			<td>
			<input type="text" name="course"/>	
			</td>
		</tr>
		<tr>
			<td align="right">
				<input type="submit" name="submit" value="save"/>
			</td>
			<td>
				<?php echo $mess; ?>
				<td>
		</tr>
	</table>
</div>
</form>

5.Add New Page use [php snippet=1] shortcut from PHP Code plugin

newpage

6. run the application

insert

7. Click the save button

success

8. Open MySQL and see the save record

mysql

Posted in PHP