Php MySql While循环如果结果?

时间:2014-06-01 17:45:01

标签: php mysql

有没有办法在使用这种风格的while循环之前判断是否有结果?

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

}

我想在while循环之前和之后做一些事情,但我不想再查询两次。

3 个答案:

答案 0 :(得分:3)

检查所选行数:$stmt->num_rows

所以你可以这样做:

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

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

答案 1 :(得分:0)

尝试

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

}

答案 2 :(得分:0)

你可以查看mysqli - > while循环前的num_rows

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