dongzhong7299 2013-12-22 08:31
浏览 40
已采纳

在fetch_array(mysqli OOP)之后获取num_rows的正确命令顺序

I'm having a problem getting a num_row when I fetch the results as an array:

$sql = "SELECT * FROM people WHERE peopleid=?";
if (!($stmt = $mysqli->prepare($sql))) {
echo "stmt Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->bind_param("i", $_GET['peopleid'])) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
   echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

$stmt->store_result();
$exist=$stmt->num_rows;
$result = $stmt->get_result();
$peopleres  = $result->fetch_array(MYSQLI_ASSOC); // this does work :)
if ($exist == 0) {
//do something it it's zero
}

If I place the store_results and num_rows where it is in the example I get an

Call to a member function fetch_array() on a non-object error.

If I place it after the fetch_array it's always equal to zero. I've used num_rows successfully before, but this is the first time I'm trying to use it alongside a fetch_array.

  • 写回答

3条回答 默认 最新

  • douganggu4392 2013-12-22 09:32
    关注

    Take a look at the documentation

    mysqli_result::$num_rows
    int $mysqli_result->num_rows;

    If you want for some reason use num_rows instead of

    $stmt->store_result();
    $exist=$stmt->num_rows;
    $result = $stmt->get_result();
    $peopleres  = $result->fetch_array(MYSQLI_ASSOC); // this does work :)
    if ($exist == 0) {
    //do something it it's zero
    }
    

    you may try

    $result = $stmt->get_result();
    $exist = $result->num_rows;
    if ($exist == 0) {
        //do something it it's zero
    }
    $row = $result->fetch_array(MYSQLI_ASSOC);
    

    Now if you're just checking whether you have any rows in the resultset or not the usage of num_rows is not absolutely necessary since you already get your resultset on the client. You can just try to fetch a row

    $result = $stmt->get_result();
    if (!$row = $result->fetch_array(MYSQLI_ASSOC)) {
        //do something if there's no row
    } else {
        //do what you have to do with you data in the row
        echo 'peopleid: ' . $row['peopleid'];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上