Hi I have a list of mysql data entries on a webpage like: 1 name1 email1 2 name2 email2 3 name3 email3 ect. How can I delete an entire row (id, name and email) from that database using a link so it will look like: 1 name1 email 1 - delete this (clicking on this link will delete this row) I Googled around and found this: http://www.totallyphp.co.uk/code/delete_data_from_a_mysql_database.htm <?php /* * Change the first line to whatever * you use to connect to the database. * * Change tablename to the name of your * database table. * * This example would delete a row from * a table based on the id of the row. * You can change this to whatever you * want. */ // Your database connection code db_connect(); $query = "DELETE FROM tablename WHERE id = ('$id')"; $result = mysql_query($query); echo "The data has been deleted."; ?> PHP: What I dont understand is how to trigger this when clicking on a link .. :?: Anyone got some suggestions? Thanks in advance!
You can use $_GET. It works like this: <?php db_connect(); if(isset($_GET['delete'])) { // checks if user visits http://watever.com/thatphp.php?delete $id = $_GET['delete']; // if the user does, check and use the variable that the user passed $query = "DELETE FROM tablename WHERE id = ('$id')"; } $result = mysql_query($query); echo "The data has been deleted."; ?> PHP: So when user visits http://watever.com/thatphp.php?delete=1 it will delete the row where id equals to 1. Of course, you have to consider security here because sql injection can definitely occur.
Create a file named delete.php (example): <?php db_connect(); //validate input... if (isset($_GET['id']) && is_numeric($_GET['id'])) { //sanitize id to prevent sql injection... $id = intval($_GET['id']); //delete.php?id=1 - this would delete the row with the id 1... $query = "DELETE FROM tablename WHERE id = '{$id}'"; //execute query... mysql_query($query); echo "The data has been deleted."; } ?> PHP: and you can then access it via delete.php?id=$id
Simply place the code in a .php file and link to it. Or you could use a get data in ur link e.g: delete.php?id=21 then you could use: However , you should be aware of security problems (users can load the link to delete other peoples accounts). I would personally not send the ID in get data as usually such data is already secured in a session / cookie somewhere. So something like this should do it:
Thanks guys I tried this code .. And it kinda works, but the thing is that it doesnt delete the row .. hmm