如何检查准备好的陈述是否有结果

wil*_*fun 2 php mysql pdo prepared-statement

在过去,我会这样做:

  $sql = 'SELECT * FROM customers WHERE customer_email="' . mysql_real_escape_string($_POST['customer_email']) . '" ';
  $res = mysql_query($sql);

  // if there are no hits...
  if(mysql_num_rows($res) == FALSE) {
Run Code Online (Sandbox Code Playgroud)

今天我用预备的陈述做了同样的事情:

  $stmt = $dbh->prepare("SELECT * FROM customers where customer_email = ? LIMIT 1");
  if ($stmt->execute(array($_POST['customer_email']))) {
Run Code Online (Sandbox Code Playgroud)

我准备好的语句的第二行if($ stmt ...是"如果此查询得到结果"或"是否"无论结果是否执行此查询,即它是否执行没有错误").

我正在尝试解决的是准备好的语句你如何做相当于mysql_num_rows()== FALSE?

谢谢!!

Jac*_*kin 7

您可以使用rowCount()方法PDOStatement获取返回的行数:

$stmt = $dbh->prepare("SELECT * FROM customers where customer_email = ? LIMIT 1");
if ($stmt->execute(array($_POST['customer_email']))) {
    if($stmt->rowCount() > 0) {
       //fetch stuff...
    }
}  
Run Code Online (Sandbox Code Playgroud)

或者,如果rowCount()证明不可靠,您可以这样做:

$all = $stmt->fetchAll();
if(count($all)) {
   //loop through the set...
}
Run Code Online (Sandbox Code Playgroud)

  • +1但请注意,`rowCount()`仅在使用缓冲查询时才有效.没有MySQL接口可以告诉您在获取结果集之前有多少行. (2认同)