问题:
This question already has an answer here:
PHP Mysql delete Query not working properly 3 answers
I tried to delete user from mysql database with thi...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
This question already has an answer here:
I tried to delete user from mysql database with this code
if (isset($_POST['user_delete'])) {
$key = $_POST['keyToDelete'];
$check = "DELETE FROM user WHERE id = ". $key or die(mysqli_error($connection));
$result2 = $connection->query($query);
if($result2->num_rows >0){
$query_delete = "DELETE FROM user WHERE id =". $key or die(mysqli_error($connection));
var_dump($query_delete);
} else {
}
but it don't want to delete my database. but the sql already right and I also got the id because I tried to var_dump it. please help what was wrong with my code
回答1:
You have a few issues here,
Your or die(mysqli_error($connection))
is to the querystrings, not the actual queries. Besides, instead of manually checking for errors it's much better to configure to throw errors automatically. For this add the following line to the connection code:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
You attempt to delete it twice? Though the second query is never executed, you just define the querystring (and never run it).
num_rows
is only usable on select-statements. You want affected_rows
to check if the query actually deleted any data.
- You're not using a prepared statement.
if (isset($_POST['user_delete'])) {
$key = $_POST['keyToDelete'];
$query = "DELETE FROM user WHERE id = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $key);
$stmt->execute();
if ($stmt->affected_rows) {
echo "Deleted ".$stmt->affected_rows." rows";
} else {
echo "No rows matched the criteria.";
}
$stmt->close();
}