13

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?

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
ollie
  • 799
  • 2
  • 10
  • 24
  • What does a var_dump on $stmt produce? – JamesHalsall Feb 16 '11 at 12:25
  • print_r() returns: mysqli_stmt Object ( [affected_rows] => -1 [insert_id] => 0 [num_rows] => 0 [param_count] => 1 [field_count] => 4 [errno] => 0 [error] => [sqlstate] => 00000 [id] => 1 ) – ollie Feb 16 '11 at 12:33
  • make sure the data is exist... – ajreal Feb 16 '11 at 13:33
  • The way I undertand it (and please correct me if I'm wrong, this is new to me) is that after $stmt->execute() is called, the query is performed and so any time after that I should be able to access the number of rows that were retrieved? I've tried echoing $stmt->num_rows after $stmt->execute() and after $stmt->fetch(). The query is definately correct because it is filling the table's cells (//code) correctly - so there is data. Thanks – ollie Feb 16 '11 at 14:12

1 Answers1

25

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).

Dharman
  • 30,962
  • 25
  • 85
  • 135
ircmaxell
  • 163,128
  • 34
  • 264
  • 314