PHP: Update Record to MySQL in wordpress CMS Using Php Code Plugin

1. MySQL database

Capture

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

php_update

3.  Complete code is here

<form action="/wordpress/update-record/" method="post">
<?php
$text="";$text1="";$text2=""; $btn="";
$hid="style='margin: auto; visibility:hidden'";
$r1="";$r2="";$r3="";$nt="";
$codeerr="";
$code="";
$flag=0;
if(isset($_POST["submit"]))
{
if(empty($_POST["t1"]))
{
$codeerr="Data Missing";
$flag=0;
}
else if(is_numeric(trim($_POST["t1"]))==false)
{
$codeerr="Accept Numeric value only";
$flag=0;
}
else
{
$code=$_POST["t1"];
$flag=1;
}
}
?>
<?php
if($flag!=0)
{
$server="localhost";
    $username="root";
	$password="";
	$dbname="wordpress";
	$cnt=0;
	try
	{
		$db=new PDO("mysql: host=$server; dbname=$dbname",$username, $password);
		$result=$db->query('select *from students where roll='.$code);

$result->setFetchMode(PDO::FETCH_ASSOC);
$row=$result->fetch();
$cnt=count($row);
if($cnt>1)
{
$hid="style='margin: auto; visibility:visible'";
$rl=$row["roll"]; 
$text="<input type='text' name='ro' value='$rl' readonly='readonly' />";
$r2=$row["name"]; 
$text1="<input type='text' name='na' value='$r2' />";
$r3=$row["course"]; 
$text2="<input type='text' name='co' value='$r3' />";
$btn=""; 
if(isset($_POST["submit"])) 
{ 
$btn="<input type='submit' name='edit' value='Update'/>";      
} 
}
else
{
echo"<h2 style=' text-align:center'>Record not Found</h2>";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
if(isset($_POST['edit']))
 {
 $rr=$_POST["ro"];
 $rn=$_POST["na"];
 $rc=$_POST["co"];

$server="localhost";
	$username="root";
	$password="";
	$dbname="wordpress";
	$cnt=0;
	
		$db=new PDO("mysql: host=$server; dbname=$dbname",$username, $password);
$stmt=$db->prepare("update students set name= '$rn', course='$rc' WHERE roll = :roll");
$stmt->bindParam(':roll',$rr);
$count=$stmt->execute(); 
if($count>0)
{
 echo "<h2 style=' text-align:center'>update record successfull.</h2>";
}
 }

?>

<div style="text-align:center" >
	<input type="text" name="t1"/>
	<input type="submit" name="submit" value="Search"/>
	<br>
	<?php echo $codeerr; ?>
	
	<table <?php echo $hid; ?> >
	<tr>
		<td>Roll No.</td>
		<td><?php echo $text; ?></td>
	</tr>
	<tr>
		<td>Name</td>
		<td><?php echo $text1; ?></td>
	</tr>
	<tr>
		<td>Course</td>
		<td><?php echo $text2; ?></td>
	</tr>
	<tr>
		<td colspan="2" style="text-align:right"><?php echo $btn; ?></td>
	</tr>
</table>
</div>
</form>

4.Add New Page use [php snippet=2] shortcut from PHP Code plugin

sndfhd

5. Run the application

upddd6. Search Student roll no which you want to update

seupdfg

 

7. Edit your field & click update

upyuo

up2228. Now check your database

databege

 

 

 

Posted in PHP