dongpo5264 2014-12-09 21:13
浏览 45
已采纳

Pdo Sqlite和php

I have a question related to php / pdo and sqlite. I have ported some code from a mysql backend to a sqlite backend. I have used rowCount() alot in this project.

In my original Mysql application i did this:

$stmt = $db->query("SELECT id FROM table where id = $id "); 
$rc = $stmt->rowCount();
if ($rc == 1) {
// do something 
    }

The documentation says this method is only for returning affected rows from UPDATE, INSERT, DELETE queries, with the PDO_MYSQL driver (and this driver only) you can get the row count for SELECT queries.

So, how to achive the same thing with a sqlite backend?

This is how I have ended up doing it:

$stmt = $db->query("SELECT count(id) as cnt FROM table where id = $id "); 
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if ($row['cnt'] == "1") {
        // do something
    } else {
        return false;
        }
    }
}

I am looking for a more elegant solution, while achieving the same thing as rowCount().

  • 写回答

1条回答 默认 最新

  • dongzhe3573 2014-12-09 21:18
    关注

    This is the way to do that in pdo:

    $stmt = $db->query('SELECT * FROM table');
    if ($stmt->rowCount() == 1) {
        //...
    } else {
        //...
    }
    echo $row_count.' rows selected';
    

    (The same way XD)

    BTW, I wouldn't recommend doing something like

    $stmt = $db->query("SELECT count(id) as cnt FROM table where id = $id "); 
    

    It's not good to have variables in statements like that. use something like:

    $stmt = $db->query('SELECT id FROM table where id = ?');
    $stmt->execute(array($id));
    if ($stmt->rowCount() == 1)
    {
        $arr = $stmt->fetch(PDO::FETCH_ASSOC);
        foreach($arr as $element)
        {
            echo '<pre>'.print_r($element).'</pre>';
        }
    }
    else
    {
        //...
    }
    

    This is part of some code I'm using:

    $stmt = $db->prepare('SELECT * FROM users WHERE id=?');
    $stmt->execute(array($id));
    if ($stmt->rowCount() == 1) {
        $currentUser = $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
    } else {
        return false;
    }
    

    Edit: (for compatibility issues)

    $stmt = $db->query('SELECT * FROM table');
    $arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (($arr === false) || (sizeof($arr) == 0)) {
        return false;
    } else {
        //... do ....
        echo sizeof($arr);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染