cannot delete database mysql with php [duplicate]

问题: 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,

  1. 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);
    
  2. You attempt to delete it twice? Though the second query is never executed, you just define the querystring (and never run it).

  3. num_rows is only usable on select-statements. You want affected_rows to check if the query actually deleted any data.
  4. 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();
}
  • 发表于 2019-07-08 00:23
  • 阅读 ( 179 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除