Count number of records in a database

3

I want to count the number of records in a database table. I have 3 records in my DB, but the result is always 1. I used this code:

$base_hndl = new SQLite3("p.sqlite");
$select = "SELECT COUNT(*) FROM users";
$resultat = $base_hndl->exec($select);                      
echo "Utilizadores conectados ".$resultat;
    
asked by anonymous 10.11.2014 / 01:13

2 answers

4

If you look at documentation you will see that the return of the exec method is of the Boolean type, that is, it will return 0 ( false ) if the operation failed or 1 ( true ) if the operation was successful. For this you always receive 1, the operation is always happening without problems.

The exec is to execute not queries , that is, to execute commands that do not give results except for the information if it occurred without problems. Typical cases are CREATE , INSERT , etc.

When you are searching for information in the database, that is, you are using SELECT you need to use methods that bring those results to a variable or can be read with other methods of the class.

To get the result you want, you'll probably need the QuerySingle method or eventually the Query . This should not be the case now, but Prepare can also be useful in other situations.

There are still other ways to access this, so check out the class documentation as a whole, you can learn a lot of cool things there, especially with the examples.

Another manual reference with more complete information and other ways to retrieve the required data using a class slightly different from the one you are using. Take a good look, it may be more advantageous to change your code to use this class.

    
10.11.2014 / 01:35
3

Try this:

$select = "select count(*) as numeroOnline from users;";
$r = $base_hndl->exec($select);
$value = $r->fetch(PDO::FETCH_ASSOC);
Echo "número online ".$value['numeroOnline'];

I always gave 1 because you were getting true or false from the exec function. This is if you are sweating PDO.

    
10.11.2014 / 01:35