Simeon
Simeon

Reputation: 878

Count method sql class not working in php

I'm trying to use an object to count the number of records in my db that meet certain criteria but I can't work out how to make it work. The following code is my count method inside my db connection class:

//Counts the total number of records and returns integer
public function totalCount($fieldname, $tablename, $where = "") 
{
    $q = "SELECT count(".$fieldname.") FROM "
    . $tablename . " " . $where;

    $result = $this->mysqli->query($q);
    $count = 0;

    if ($result) {
        while ($row = mysqli_fetch_array($result)) {
            $count = $row[0];
        }
    }
    return $count;
}

This code is outside the class:

 //New instantiation
 $mydb = new myDBC();

 //Count the number of transactions for the user...
 $count = $mydb->totalCount('amount','transactions','WHERE userid = 13');

 //output the number of transactions for the user
 print $count;

For some reason this always displays 0, even though my db has thousands of records inside it that should be counted. Grateful for any pointers as to where my syntax isn't right.

Thanks

Upvotes: 0

Views: 86

Answers (3)

user2672373
user2672373

Reputation:

You can use prepared statement to prepare the query and then execute it. And, I don't think that it is essential to pass a field as argument to COUNT.

Anyway, as per your question, this would make a better query.

$q = 'SELECT COUNT( * ) FROM ' . $strTable . ' WHERE ' . $strCond;

Again, since you are using MySQLi, use prepared statements.

Upvotes: 0

Param
Param

Reputation: 1

Query execution returning false and it's not going inside if conditions thats why count is always zero

Upvotes: 0

Nicolai
Nicolai

Reputation: 5797

Does this method returns zero for all tables/fields or you tested only

$mydb->totalCount('amount','transactions','WHERE userid = 13');?

The count counts only NOT NULL values. To count all records pass asterisk to the count function: count(*)

Upvotes: 1

Related Questions