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

The original page this is from was down at the time of this writing, so I want to mirror it here.

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 "$title - Delete“;
echo “
“;
}
}
?>

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.

This entry was posted on Thursday, November 15th, 2007 at 1:27 pm and is filed under Web Development. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “PHP Tutorials: Delete a Row From mySQL”

  1. drt on November 16th, 2007 at 8:51 am

    Saw you spent time writing this. Are you planning to write a book on PHP? Just curious. :lol:

Leave a Reply