1

Is there a way to tell if there is results before the while loop using this style?

$stmt = $mysqli->prepare("SELECT * FROM items WHERE type = ?");
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one,$two,$three); 
while ($stmt->fetch()) {

}

I would like to do something before and after the while loop but I do not want to query twice.

1
  • use mysqli_num_rows to check if the result is present Commented Jun 1, 2014 at 17:47

3 Answers 3

3

To check the number of rows selected: $stmt->num_rows

So you might do:

if($stmt->num_rows > 0){
    ...
}

http://www.php.net/manual/en/mysqli-stmt.num-rows.php

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you, and much simpler than I expected.
0

Try

stmt = $mysqli->prepare("SELECT * FROM items WHERE type = ?");
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one,$two,$three); 

$rows = $stmt->num_rows;
if ($rows) {
   // your code
}

while ($stmt->fetch()) {

}

1 Comment

What's the benefit of copying it to another variable?
0

you can check with mysqli -> num_rows before while loop

$stmt = $mysqli->prepare("SELECT * FROM items WHERE type = ?");
$stmt->bind_param('s', $type);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($one,$two,$three); 

$numrows = $stmt->num_rows;
if ($numrows > 0) {

  while ($stmt->fetch()) {

  }
} else {
   echo "No rows found";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.