简体   繁体   English

在PHP中使用SQlite3如何计算结果集中的行数?

[英]Using SQlite3 in PHP how to count the number of rows in a result set?

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) 但结果是1,它应该是6(我用firefox sqlite3插件创建的行数)

Can anybody help please? 有人可以帮忙吗?

$db = new SQLite3('filename.db3');
$count = $db->querySingle("SELECT COUNT(*) as count FROM tablename");
echo $count;

From the documentation : 文档

public bool SQLite3::exec ( string $query ) 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 . 当您将true转换为整数时,它将变为1

You should use SQLite3::query() . 您应该使用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). 顺便说一句,命名SQLite3类$result的实例可能会产生误导(特别是在数据库环境中)。 I would call it $db or $connection . 我会称之为$db$connection

$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
    }
<?php
    function SqliteNumRows($query){
        $numRows = 0;
        while($rows = $query->fetchArray()){
            ++$numRows;
        }
        return $numRows;
    }
?>

This really helped me it works actually you may try it 这真的帮助了我实际上你可以尝试它

Here is a working way to get the number of rows since neither sqlite_num_rows($result) nor $result->numRows() works on SQLite3: 这是获取行数的一种工作方式,因为sqlite_num_rows($result)$result->numRows()适用于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(*)"];
        }
?>

It's have benefit, when you have conditions in the count select query: 当您在计数select查询中有条件时,它有好处:

$stmt = $db->prepare('SELECT COUNT(*) AS `count` FROM `tablename` WHERE `foo`=:foo');
$stmt->bindValue(':foo', $foo);
$stmt->execute();
$count = $stmt->fetchColumn();
echo $count;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM