PHP Tutorials

XMLStyleSoldierFlowerMonkey

Delete a Row From mySQL

Learn how to remove a row in mySQL using the power of PHP.

Spreadshirt
Here is an easy PHP script to delete any row from your Database. This tutorial goes along with several others that use the same news database such as Add a Row to mySQL, Displaying a Database, and Edit a Row In mySQL. We have a database called spoono_news, with a table called news. In the mySQL news table, we have 6 fields: id, title, message, who, date, and time. You can see the mySQL code here: mysql.txt.This tutorial can be broken down into two sections. Both of the sections can be put on the same page. Open up a new HTML page, save it as delete.php and write all this inside the Body tag. You can see my code that I worked on and made sure worked by right clicking and saving delete.txt. The first shows you all the rows inside the database with a radio button next to them which you can select to delete a row. The second processes it and deletes it.

Here is what we have to write in English to pick a row to delete:
  1. Connect to the mySQL
  2. If a command to delete has not been initialized, then display all the news posts
  3. When displaying, make the title a link that would go to delete that particular post
Here it is in PHP:
<? 
//connect to mysql
//change user and password to your mySQL name and password
mysql_connect("localhost","user","password"); 
	
//select which database you want to edit
mysql_select_db("spoono_news"); 

//If cmd has not been initialized
if(!isset($cmd)) 
{
   //display all the news
   $result = mysql_query("select * from news order by id"); 
   
   //run the while loop that grabs all the news scripts
   while($r=mysql_fetch_array($result)) 
   { 
      //grab the title and the ID of the news
      $title=$r["title"];//take out the title
      $id=$r["id"];//take out the id
     
	 //make the title a link
      echo "<a href='delete.php?cmd=delete&id=$id'>$title - Delete</a>";
      echo "<br>";
    }
}
?>
And that is basically all the code we have to write to find the ID for which one you want to delete. Now here is the processing in English:
  1. If the cmd is set to delete, then delete from the database
  2. Send a confirmation.
Here it is in PHP:
<?
if($_GET["cmd"]=="delete")
{
    $sql = "DELETE FROM news WHERE id=$id";
    $result = mysql_query($sql);
    echo "Row deleted!";
}
?>
You can see my code that I worked on and made sure worked by right clicking and saving delete.txt. Not too tough was it? Well thats it folks. I hope it works out for you and if it doesn't, email for help at webmaster@spoono.com and we'll try to help you out.

Discuss this tutorial »
Written by: Akash Goel
Back to PHP TutorialsTop


Copyright © 2000-2008 Spoono, LLC. All rights reserved.
Network: Reseller Web Hosting by Spoono Host | Spoonloads | Absolute Cross
Terms of Service | Privacy Policy.

kdfj