dongyan1974 2015-03-30 15:21
浏览 52

检查PDO prepare(),execute()是否返回至少一行

Before moving to PDO, I used

$result = mysqli_query ($conn, 'SELECT * FROM mytable WHERE id = 54');
if (mysqli_num_rows($result) >= 1) { ... }

to check if the query returns at least one result.

Now with PDO, I've seen in many SO questions (like get number of rows with pdo) that there is no direct function in PDO to check the number of rows of a query (there are warnings about the use of$result->rowCount();), but rather solutions like doing an extra query:

SELECT count(*) FROM mytable WHERE id = 54

But this is maybe too much for what I want : in fact, I don't need the exact number of rows, but just if there is at least one.

How to check if a prepared statement query returns at least one row ?

$stmt = $db->prepare('SELECT * FROM mytable WHERE id = 54');
$stmt.execute();
... // HOW TO CHECK HERE?
  • 写回答

1条回答 默认 最新

  • dpqmu84646 2015-03-30 15:31
    关注
    $stmt = $db->prepare('SELECT * FROM mytable WHERE id = 54');
    $stmt.execute();
    ... // HOW TO CHECK HERE?
    

    It's so simple, you're almost there already.

    $stmt = $db->prepare('SELECT * FROM mytable WHERE id = 54');
    $stmt.execute();
    $result = $stmt->fetchAll();  // Even fetch() will do
    if(count($result)>0)
    {
          // at least 1 row
    }
    

    And if you just want Yes/No answer then you should also add a LIMIT 1 to your query so mysql doesn't waste trying to look for more rows.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度