num_rows: get_result vs store_result

后端 未结 1 431
别跟我提以往
别跟我提以往 2021-01-25 15:22

The following code returns 0, even though there are 5 entries in the table categories with cat = 1.

$sql = \"SELECT name FROM categ         


        
相关标签:
1条回答
  • 2021-01-25 16:25

    Looks like the other answer is wrong and get_result doesn't change the state of a statement (which is quite logical, as you are asking for mysqli_result and therefore supposedly going to work with it from now on).

    You see, the way you are using get_result is quite pointless. To make any point of it, you have to assign the result to a variable, which will give you the desired outcome:

    $res = $stmt->get_result();
    echo $res->num_rows;
    

    Note that the num_rows property is quite useless in general. If you want to know whether your query returned any data or not, just collect the rows into array and then you use this array for the purpose.

    $data = $stmt->get_result()->fetch_all();
    if ($data) {
        // whatever
    } else {
        // oops!
    }
    

    And of course you shouldn't use such a query only to count the goods available in a category. For such a purpose a count(*) query have to be used.

    0 讨论(0)
提交回复
热议问题