【问题标题】:How to check if there are results with Prepared Statements如何使用Prepared Statements检查是否有结果
【发布时间】:2010-09-16 00:41:32
【问题描述】:

过去我会这样做:

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

今天我正在做同样的事情,但是使用准备好的语句:

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

我准备好的语句 if($stmt... 的第二行是“如果这个查询得到一个结果”还是“如果这个查询不管结果如何都被执行,即如果它执行没有错误”。

我要解决的是使用准备好的语句,您如何执行相当于 mysql_num_rows() == FALSE 的操作?

谢谢!!

【问题讨论】:

    标签: php mysql pdo prepared-statement


    【解决方案1】:

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

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

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

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

    【讨论】:

    • rowCount() 是一种方法,官方只支持操作中受影响的行,但是是的,对于 MySQL,它作为结果集中的行数起作用。
    • +1 但请注意,rowCount() 仅在您使用缓冲查询时才有效。 MySQL 的任何接口都无法告诉您在获取结果集中有多少行。
    • 稍有不同,您如何看待最终查询的样子?即,如果我想查看我正在执行的操作以检查变量是否正确通过,我会去“echo $sql” - 执行此操作的 PDO 方法是什么?
    【解决方案2】:

    PDOStatement::rowCount() 返回受 DELETE、INSERT 或 UPDATE 语句影响的行数,而不是 select 查询返回的行数, 对于我使用的选择查询:
    fetchAll(PDO::FETCH_OBJ);echo count($lignes);

    <?php
    $PARAM_hote='localhost'; 
    $PARAM_port='3306';
    $PARAM_db='test'; 
    $PARAM_user='root'; 
    $PARAM_pwd=''; 
    try
    {
    $connexion = new PDO('mysql:host='.$PARAM_hote.';dbname='.$PARAM_db, $PARAM_user,$PARAM_pwd);
    }
    catch(Exception $e)
    {
    echo 'Erreur : '.$e->getMessage().'<br />';
    echo 'N° : '.$e->getCode();
    }
    $requete_prepare_1=$connexion->prepare("SELECT * FROM `test_mysql`"); 
    $requete_prepare_1->execute();
    $lignes=$requete_prepare_1->fetchAll(PDO::FETCH_OBJ);
    echo count($lignes); 
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-25
      • 2012-07-25
      • 2012-08-23
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      相关资源
      最近更新 更多