Jptalon
Jptalon

Reputation: 99

Php MySql While loop if result?

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.

Upvotes: 1

Views: 101

Answers (3)

fortune
fortune

Reputation: 3372

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";
}

Upvotes: 0

Hayk Manasyan
Hayk Manasyan

Reputation: 506

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()) {

}

Upvotes: 0

Andrew
Andrew

Reputation: 20081

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

Upvotes: 3

Related Questions