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 写uniapp时遇到的问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流