dongya1875 2010-09-16 00:41
浏览 41
已采纳

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

In the past I would do something like so:

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

Today I am doing the same thing however with prepared statements:

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

The 2nd line of my prepared statement if($stmt... is that "if this query gets a result" or is it "if this query is executed regardless of results or not ie if it executes without error".

What I'm trying to work out is with prepared statements how do you do the equivalent of mysql_num_rows() == FALSE?

Thanks!!

  • 写回答

2条回答 默认 最新

  • dongsou4301 2010-09-16 00:46
    关注

    You can use the rowCount() method of PDOStatement to get the number of rows returned:

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

    Or, if rowCount() proves to be unreliable, you can do this:

    $all = $stmt->fetchAll();
    if(count($all)) {
       //loop through the set...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding