DELETE FROM table WHERE ID='$id' — Variable refuses to stick
Trying to perform a very simple task here.
I have an <ol>
that contains 4 rows of data in some handy <li>
s. I want to add a delete button to remove the row from the table. The script in delete.php appears to have finished, but the row is never removed when I go back and check dashboard.php and PHPMyAdmin for the listing.
Here's the code for the delete button (inside PHP):
Print "<开发者_如何学编程;form action=delete.php method=POST><input name=".$info['ID']." type=hidden><input type=submit name=submit value=Remove></form>";
Moving on to delete.php:
<?
//initilize PHP
if($_POST['submit']) //If submit is hit
{
//then connect as user
//change user and password to your mySQL name and password
mysql_connect("mysql.***.com","***","***") or die(mysql_error());
//select which database you want to edit
mysql_select_db("shpdb") or die(mysql_error());
//convert all the posts to variables:
$id = $_POST['ID'];
$result=mysql_query("DELETE FROM savannah WHERE ID='$id'") or die(mysql_error());
//confirm
echo "Patient removed. <a href=dashboard.php>Return to Dashboard</a>";
}
?>
Database is: shpdb Table is: savannah
Ideas?
It's refusing to stick because you're calling it one thing and getting it with another. Change:
"<input name=".$info['ID']." type=hidden>"
to
"<input name=ID value=".$info['ID']." type=hidden>"
because in delete.php you're trying to access it with:
$id = $_POST['ID'];
You should really quote attribute values as well ie:
print <<<END
form action="delete.php" method="post">
<input type="hidden" name="ID" value="$info[ID]">
<input type="submit" name="submit" value="Remove">
</form>
END;
or even:
?>
form action="delete.php" method="post">
<input type="hidden" name="ID" value="<?php echo $info['ID'] ?>">
<input type="submit" name="submit" value="Remove">
</form>
<?
Please, for the love of the web, don't built an SQL query yourself. Use PDO.
Just another point I'd like to make. I'm 95% sure that you can't give an input a numeric name/id attribute. It has to be like "id_1" not "1".
Also with php you can do arrays.
So you could do this
<input name="delete[2]">
then in your php
if(isset($_POST['delete']))
foreach($_POST['delete'] as $key=>$val)
if($_POST['delete'][$key]) delete from table where id = $val
精彩评论