Using SQlite3 in PHP how to count the number of ro

2019-01-09 07:23发布

currently I am using:

$result = new SQLite3(sprintf("users/USERIDS_DB.sqlite"));

$numRows = $result->exec ("SELECT count(*) FROM USERIDS");

echo sprintf("the number of rows are: %d", $numRows);

but the result is 1 when it should be 6 (the number of rows I created using firefox sqlite3 addon)

Can anybody help please?

6条回答
相关推荐>>
2楼-- · 2019-01-09 08:10

From the documentation:

public bool SQLite3::exec ( string $query )

Executes a result-less query against a given database.

This methods returns a boolean, not a result set. When you convert true to an integer it will become 1.

You should use SQLite3::query(). Example (untested):

$rows = $result->query("SELECT COUNT(*) as count FROM USERIDS");
$row = $rows->fetchArray();
$numRows = $row['count'];

Btw, naming the instance of the SQLite3 class $result can be misleading (especially in a DB environment). I would call it $db or $connection.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-09 08:14

It's have benefit, when you have conditions in the count select query:

$stmt = $db->prepare('SELECT COUNT(*) AS `count` FROM `tablename` WHERE `foo`=:foo');
$stmt->bindValue(':foo', $foo);
$stmt->execute();
$count = $stmt->fetchColumn();
echo $count;
查看更多
Bombasti
4楼-- · 2019-01-09 08:19

Here is a working way to get the number of rows since neither sqlite_num_rows($result) nor $result->numRows() works on SQLite3:

<?php
     $db = new SQLite3('database.db');

    $results = $db->query('SELECT COUNT(*) FROM (SELECT `id`,* FROM `table` ORDER BY `id` ASC);');
        while ($row = $results->fetchArray()) {
           echo $row["COUNT(*)"];
        }
?>
查看更多
该账号已被封号
5楼-- · 2019-01-09 08:22
$db = new SQLite3('filename.db3');
$count = $db->querySingle("SELECT COUNT(*) as count FROM tablename");
echo $count;
查看更多
爷、活的狠高调
6楼-- · 2019-01-09 08:23
$result = $db->query("SELECT * FROM db_name")
$row=$result->fetchArray(SQLITE3_ASSOC);
    // check for empty result
    if ($row != false) {
      // do something here if record exists
    }
查看更多
一夜七次
7楼-- · 2019-01-09 08:23
<?php
    function SqliteNumRows($query){
        $numRows = 0;
        while($rows = $query->fetchArray()){
            ++$numRows;
        }
        return $numRows;
    }
?>

This really helped me it works actually you may try it

查看更多
登录 后发表回答