Why does mysqli num_rows always return 0?

2020-01-23 10:44发布

问题:

I've been having trouble getting the number of rows to return using mysqli. I just get 0 back every time even though there are definitely some results.

if($stmt = $mysqli->prepare("SELECT id, title, visible, parent_id FROM content WHERE parent_id = ? ORDER BY page_order ASC;")){  
    $stmt->bind_param('s', $data->id);  
    $stmt->execute();
    $num_of_rows = $stmt->num_rows;  
    $stmt->bind_result($child_id, $child_title, $child_visible, $child_parent);  

    while($stmt->fetch()){
        //code
    }

    echo($num_of_rows);

    $stmt->close();
}

Why doesn't it show the correct number?

回答1:

You need to call MySqli_Stmt::store_result() prior to the num_rows lookup:

if($stmt = $mysqli->prepare("SELECT id, title, visible, parent_id FROM content WHERE parent_id = ? ORDER BY page_order ASC;")){  
    $stmt->bind_param('s', $data->id);  
    $stmt->execute();
    $stmt->store_result(); <-- This needs to be called here!
    $num_of_rows = $stmt->num_rows;  
    $stmt->bind_result($child_id, $child_title, $child_visible, $child_parent);  

    while($stmt->fetch()){
        //code
    }

    echo($num_of_rows);

    $stmt->close();
}

See the docs on MySQLi_Stmt->num_rows, it says it right near the top of the page (in the main description block)...



回答2:

Try setting your $num_of_rows right after your if(statement) - before bind_param... Unless that's changing your results. Hard to tell without more info.



标签: php mysqli