|
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: Connect to the mySQL If a command to delete has not been initialized, then display all the news posts 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 xhref='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: If the cmd is set to delete, then delete from the database 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!"; } ?>
Credit: www.spoono.com
|