Brandon
Brandon

Reputation: 125

How to delete a row from mysql via php

Brushing up on php and working on a simple program where I've run into an issue. I can't seem to figure out how to delete a mysql row. I will link my script in a pastie document so you can see how I have it set up.

I'm not familiar with AJAX or Javascript.. so I just made the delete button a form. I'd like to keep it like this for now if I can make it work.

PASTIE HERE

Upvotes: 0

Views: 289

Answers (3)

Nir Alfasi
Nir Alfasi

Reputation: 53525

change:

mysql_query("DELETE FROM name WHERE name=.'$del'.");

to:

mysql_query("DELETE FROM name WHERE name='".$_POST['$del']."'");

becuase:
1. you should get rid of the . inside the query, dot is used for string concatenation.
2. you want to use the value of $_POST['$del'] - the parameter $del is not set

Updates:

  1. change <input type="hidden" name="del" /> to: <input type="hidden" name="del" value="theNameYouWantToDelete"/>
  2. you give the same name to all the form elements (name="del") - this is not recommended! better set a different name to each object.
  3. please do not use mysql_* - it's deprecated and vulnerable to sql-injection, use PDO or MySQLi instead.

Upvotes: 2

Sean
Sean

Reputation: 12433

On line 30 you have two inputs named del, and the second one does not contain the name to delete

echo '<form id="del" method="post"><input type="submit" name="del" value="X" /><input type="hidden" name="del" /></form>';

Need to change to something like -

echo '<form id="del" method="post"><input type="submit" name="del_submit" value="X" /><input type="hidden" name="del" value="'.$del.'" /></form>';

Then change lines 12-13 to

if (isset($_POST['del_submit'])) {
mysql_query("DELETE FROM name WHERE name='".$_POST['del']."'");

Please note that mysql_ functions are depreciated, and you are subject to sql injection.

Upvotes: 0

Blake
Blake

Reputation: 1741

You're not properly concatenating the $del variable. You could simply use:

mysql_query("DELETE FROM name WHERE name='$del'");

Also, you need to set $del before the DELETE query. That variable hasn't been declared before you tried to use it, so it will be null.

Upvotes: 0

Related Questions