Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

sqlite

count

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?

like image 819
Remover Avatar asked Apr 06 '10 16:04

Remover


People also ask

How do I count rows in SQLite?

SQLite Count(*) Function In SQLite the Count(*) function will return total number of rows available in a table, including the rows which contain NULL values. The Count(*) will not take any parameters other than the asterisk symbol (*).

How many rows of data can SQLite handle?

The max_page_count PRAGMA can be used to raise or lower this limit at run-time. The theoretical maximum number of rows in a table is 264 (18446744073709551616 or about 1.8e+19). This limit is unreachable since the maximum database size of 281 terabytes will be reached first.


4 Answers

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.

like image 88
Felix Kling Avatar answered Oct 04 '22 17:10

Felix Kling


$db = new SQLite3('filename.db3');
$count = $db->querySingle("SELECT COUNT(*) as count FROM tablename");
echo $count;
like image 30
RoboTamer Avatar answered Oct 04 '22 16:10

RoboTamer


$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
    }
like image 32
fordiy Avatar answered Oct 04 '22 16:10

fordiy


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

This really helped me it works actually you may try it

like image 34
Simbarashe D Andrea Avatar answered Oct 04 '22 18:10

Simbarashe D Andrea