如何测试MySQL查询修改数据库表数据是否成功? [英] How to test if a MySQL query was successful in modifying database table data?

查看:83
本文介绍了如何测试MySQL查询修改数据库表数据是否成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的 php 代码片段,它会在调用时从数据库中删除相关文章.结果被传递给一个 javascript 函数,该函数将通过 AJAX 更新页面.如果查询失败,我想返回字符串 false,如下所示.

I have the following simple php code snippet, which will, when called, delete a relevant article from a database. The result is passed to a javascript function, which will update the page via AJAX. I would like to return the string false if the query fails, as I've below.

if($cmd=="deleterec"){
    $deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
    if ($delRecord = $con->prepare($deleteQuery)) {
        $delRecord->bind_param("s", $pk);
        $delRecord->execute();
        $delRecord->close();
        echo "true";
    } else {
        echo "false";
    }
}

我想知道我遗漏了什么以及检查查询是否成功的正确方法.

I would like to know what I have missed and the correct way to check if a query was successful or not.

推荐答案

你需要使用 mysqli->affected_rows() 用于检查查询是否成功(或者您可以使用 mysqli_stmt->execute() 的结果值.

You need to use mysqli->affected_rows() for checking if the query was successful (or you could use mysqli_stmt->execute()'s result value).

以你的例子为例,除了上面的内容什么都不修改:

Taking your example, and modifying nothing but for the above:

if($cmd=="deleterec") {
    $deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
    
    if ($delRecord = $con->prepare($deleteQuery)) {
        $delRecord->bind_param("s", $pk);
        $delRecord->execute();
    
    
        if ($delRecord->affected_rows > 0) {
            echo "true";
        } else {
            echo "false";
        }

        $delRecord->close();
    }
}

这篇关于如何测试MySQL查询修改数据库表数据是否成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆