【问题标题】:Count number of returned rows in OOP PHP计算 OOP PHP 中返回的行数
【发布时间】:2015-08-15 18:24:00
【问题描述】:

我正在使用 MySQL 学习 OOP PHP。我正在尝试运行一个应该打印返回的行数的查询。我的php代码如下:

$con=  mysqli_connect('localhost','root','','dealinte_cms') or die(mysqli_error());
$email="joy1@gmail.com";
if($r=$con->prepare("SELECT * FROM user WHERE email=? ")){
$r->bind_param("s",$email);
    if(!$r->execute()){
        echo mysqli_errno($con);
    }
    else{
        $rowCount=$r->num_rows;
        echo $rowCount;
    }
}

在我的数据库中,电子邮件是 4 行,所以 它应该打印 4,但它显示 0

我的代码有什么问题?

【问题讨论】:

    标签: php mysql oop mysqli


    【解决方案1】:

    您需要使用store_result() 存储结果。阅读更多here

    所以你的代码应该是这样的:

    <?php
    $con=  mysqli_connect('localhost','root','','dealinte_cms') or die(mysqli_error());
    $email="joy1@gmail.com";
    if($r=$con->prepare("SELECT * FROM user WHERE email=? ")){
    $r->bind_param("s",$email);
        if(!$r->execute()){
            echo mysqli_errno($con);
        }
        else{
            $r->store_result();
            $rowCount=$r->num_rows;
            echo $rowCount;
        }
    }
    ?>
    

    【讨论】:

      【解决方案2】:

      你必须store result

       $r->store_result();
      

      同样,您检查行数之前。请参阅手册页上的此说明

      请注意,有时会错过阅读此功能的重要手册条目的人:

      如果你不使用mysqli_stmt_store_result(),并且在执行一个prepared statement后立即调用这个函数,这个函数通常会返回0,因为它无法知道结果集中有多少行,因为结果集中没有还保存在内存中。

      提示

      由于您正在使用 mysql 学习 OOP PHP,因此请务必注意,您创建的与 mysql 的连接采用过程式语法。虽然在 PHP 中你可能会逃脱,但在许多其他语言中你不会。为什么不现在把它转换成 OOP 语法呢?

      $con= new mysqli('localhost', 'my_user', 'my_password', 'my_db');
      

      【讨论】:

      • 哦,我不知道。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2015-09-13
      • 2014-03-27
      • 1970-01-01
      • 2013-12-16
      • 2021-06-04
      相关资源
      最近更新 更多