检查是否在PDO中执行了SQL查询 [英] checking if SQL query was excuted in PDO

查看:87
本文介绍了检查是否在PDO中执行了SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在mysql_query中,我们可以通过以下操作检查查询是否已执行:

in mysql_query we can check if the query was executed or not by doing this:

$query = $yourdbconnection->fetch_array(mysql_query("SELECT * FROM tbl_name"));
if ($query){ // query is working }
else { // query is not working }

在PDO中,我正在执行以下操作:

in PDO, I am doing something like this:

$query = $yourdbconnection->query("SELECT * FROM tbl_name");
$fetchquery = $query->fetchAll();
if ($fetchquery) { // query is working}
else { // query not working}

我的代码有效吗? if语句到底在做什么?它正在执行与mysql_query相同的操作吗?如何检查查询是否返回0行?

Is my code effective? what exactly the if statement doing? Is it doing the same thing that mysql_query was doing? How can I check if the query is returning 0 rows or not?

我发现这些解决方案可以解决该问题

I have found those solutions as a workaround to the problem

  1. 使用$stmt->fetch()

if ($data = $stmt->fetch()) {
    do {
        echo $data['model'] . '<br>';
    } while ($data = $stmt->fetch());
} else {
    echo 'Empty Query';}

?>

  • 添加另一个查询以计算行数,请参见此答案

    ?>

  • adding another query to count the number of rows see this answer

    但是,我仍在寻找更好的解决方案

    However, I am still looking for better solutions

    推荐答案

    要查看您的查询是否已执行,建议您将PDO设置为异常模式(如您的常识"建议的那样).您可以这样做:

    To see if your query was executed, I would suggest setting your PDO in exception mode like Your Common Sense suggested. You can do it like this:

    $dbh = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    关于检查查询是否在PDO中返回值的最佳方法,我建议只执行SELECT COUNT(*) FROM table查询,如下所示:

    Concerning the best way to check if a query returned values or not in PDO, I suggest just doing a SELECT COUNT(*) FROM table query, like this:

    <?php
    $query = $dbh->query('SELECT COUNT(*) FROM table');
    if ($query->fetchColumn() != 0) {
        /* Query has result(s) */
        $query = $dbh->query('SELECT * FROM table');
        /* ... */
    } else {
        /* Query has no results */
    }
    ?>
    

    如果您还有其他问题,请告诉我.

    Let me know if you have any other questions.

    这篇关于检查是否在PDO中执行了SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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