0

I need to make a query in my SQLite3 database using PHP and this is my code and it's working:

# Set access to data base...
$db = new SQLite3('./Data/myDB.sqlite');

# Set the query  ...
$q="SELECT * FROM my_table WHERE key = '123'";

# Prepare for the query ...
$stmt = $db->prepare($q);

# Execute the query ...
$results = $stmt->execute();

Now, how to count how many records there are in my result? Suggestions / examples?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Cesare
  • 1,629
  • 9
  • 30
  • 72
  • 1
    quicker to search before you ask –  Feb 22 '18 at 19:36
  • Wow, nothing in the manual. Would have expected `num_rows` or similar but seems to be missing. You either need to loop result or `SELECT count(*) ...` – AbraCadaver Feb 22 '18 at 19:39
  • 1
    Note, you should be using prepared statements with bound parameters or else your query is open to SQL injection attacks: http://php.net/manual/en/sqlite3stmt.bindvalue.php – Mike Feb 22 '18 at 19:39
  • @AbraCadaver Weird, right? I was thinking the same thing. – Mike Feb 22 '18 at 19:41

1 Answers1

0

You could either do it in SQL or in PHP:

Change your SQL request to

SELECT COUNT(*) FROM my_table WHERE key = 123

Or count rows in PHP (taken from here) :

$nrows = 0;
$result->reset();
while ($result->fetchArray())
    $nrows++;
$result->reset();
return $nrows;
gogaz
  • 2,323
  • 2
  • 23
  • 31