PHP: Delete Record from MySQL in wordpress CMS Using Php Code Plugin

1. MySQL database

asfeef

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

PHP_code_delete

3.  Complete code is here

<form action="/wordpress/delete-record/" method="post">
<?php

$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');

$result->setFetchMode(PDO::FETCH_ASSOC);

echo "<table width='500px'  style='margin:auto;text-align:center;'>";
 echo "<tr >";
 echo"<tr><th>Roll No.</th><th>Name</th><th>Course</th></tr>";



	 while($rows = $result->fetch())
	 {
		
		echo "<tr>";
		echo "<td>".$rows['roll']."</td>
		     <td>".$rows['name']."</td>
		     <td>".$rows['course']."</td>			 
			  <td><input type='submit' value='Delete' name='".$rows['roll']."'/></td>";
			
		echo "</tr>"; 
		
		
		if(isset($_POST[$rows['roll']]))
 	 {
	 $rr=$rows['roll'];
	$server="localhost";
	$username="root";
	$password="";
	$dbname="wordpress";
	$cnt=0;
	
	$db=new PDO("mysql: host=$server; dbname=$dbname",$username, $password);	
		$stmt=$db->prepare("delete from students where roll = :roll");
		$stmt->bindParam(':roll',$rr);		
		$count=$stmt->execute(); 
		if($count>0)
		{
		echo "record deleted";
		echo '<script type="text/javascript">location.reload(true);</script>';
	
		}
		
	  }
	
	 }
	 echo "</table>";
	 }


catch(PDOException $e)
{
	echo $e->getMessage();
}

?>
</form>



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

add_snippet

5. Run the application

delete_php

6. Click Delete Button which record you want to delete

deleted_php

101 roll no. record deleted..

7. Check Your database

After_deleted_php

 

Posted in PHP