简体   繁体   中英

Get count of Mysql rows in PHP

In the below code when I var_dump($result) I can see the data I want is in there... but I have yet to be able to get to it.

Code:

try {   
    $query = new dbquery(Connection::make($dbconfig['dbinfo']));
    $count = $query->runSQL("select count(*) from table_name");

    $result = $count->fetchAll();
    var_dump($result);
    echo $result[0];
    echo $result[1];
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

SQL:

public function runSQL($sql, $params = NULL) {
    //Prepares the SQL Statement you pass through
    $statement = $this->pdo->prepare($sql);

    //Binds the Parameters I pass through on execute, so no need for seperate $statement->bindParam()
    $statement->execute($params);

    //Returns the statement.
    return $statement; 
}

output of var_dump:

array(1) { [0]=> array(2) { ["count(*)"]=> string(1) "3" [0]=> string(1) "3" } } Array

it's the ["count(*)] key I need, the value 3

I've tried the below and none gives me the right value:

echo $result[0];
echo $result[1];
echo $result['count(*)'];

Can anyone please advise where I am going wrong, all i want to know is the number of rows.

You are getting array inside an array as result. You can do the following:

echo $result[0][0];

OR

echo $result[0]['count(*)'];

Note that it is a good habit to do Aliasing in the query, for better readability. For eg, COUNT(*) can be aliased as total_count :

$count = $query->runSQL("select count(*) AS total_count from table_name");

Now, you can access the total row count as follows:

echo $result[0]['total_count'];

You need to avoid use of fetchAll in cases that only returns 1 row (COUNT, SUM or any group functions)

You can use

echo $result[0][0];

Or

$result = $count->fetchOne(); #or $count->fetch(); read the docs to the right method
echo $result[0];

获取行数的SQL命令是

select count(*) as alias from table_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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