PHP won't delete from MySQL
The PHP code won't delete item from database u开发者_开发技巧sing "$noteid". If I put a number in it's place it will, but when I try using "$noteid". It won't do it. It does everything correct up to the point where it tries to delete.
Here's how I get the "$noteid":
//javascript
function viewnote(noteid) {
window.location = "noteview.php?noteid=" + noteid;
}
//button in body
<input type="button" value="Edit" onclick="editnote('<?= $noteid ?>')" />
Here's the code on the linked to page:
<?php
$noteid = $_REQUEST['noteid'];
if (isset($_POST['delete'])){
mysql_query("DELETE FROM notes WHERE noteid='$noteid'");
header ('Location: index2.php');
}
?>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="margin:0px; pading:0px"><input type="submit" name="delete" value="Delete"></form>
</body>
** It's Working Now!!! ** What made it work was a hidden form field.
Here's the code:
<?php
if (isset($_POST['delete'])){
$nid = $_REQUEST['notenum'];
mysql_query("DELETE FROM notes WHERE noteid='$nid'");
header ('Location: index2.php');
}
?>
//body cody
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="margin:0px; pading:0px"><input type="text" name="notenum" value="<?php echo $noteid; ?>" style="display:none" /><input type="submit" name="delete" value="Delete"></form>
Thanks to everyone for your help!!! This site is my favourite site now.
You're using a lot of bad practices:
<?= $noteid ?>
That is not supported on all PHP versions, use the following instead:
<?php echo $noteid; ?>
Secondly,
mysql_query("DELETE FROM notes WHERE noteid='$noteid'");
STOP RIGHT THERE. Go learn about SQL injection before coding. I'm not joking. The right code:
mysql_query('DELETE FROM notes WHERE noteid="'.mysql_real_escape_string($noteid).'"');
Also ensure that the PHP variable $noteid
does exist prior to onclick="editnote(...)" />
.
The problem you have is that $_REQUEST['noteid']
won't be set after the form has posted. In that scenario you could add a hidden form field to store the value from the query string. You also need to look at sanitising your variable with mysql_real_escape_string
and using $_GET
or $_POST
rather than $_REQUEST
Please consider using Binds and Prepared statements. Almost all problems of the from "x from PHP doesn't work right in SQL" can be solved by using prepared statements.
精彩评论