PHP MySQL Count Query Result is String, Not Integer
I have the following MySQL query, and PHP code to format the Count
result in a single array:
$equalDimensions_query =
"SELECT 'allEqual' AS COL1,COUNT(*) AS imgCount FROM (
SELECT imgHeight, imgWidth, imgId AS primaryId FROM primary_images
UNION ALL
SELECT imgHeight, imgWidth, primaryId FROM secondary_images
) AS union_table
WHERE primaryId = $imgId AND imgWidth = $maxImageWidth AND imgHeight = $maxImageHeight
UNION ALL
SELECT 'widthEqual' AS COL1,COUNT(*) AS imgCount FROM (
SELECT imgHeight, imgWidth, imgId AS primaryId FROM primary_images
UNION ALL
SELECT imgHeight, imgWidth, primaryId FROM secondary_images
) AS union_table
WHERE primaryId = $imgId AND imgWidth = $maxImageWidth AND imgHeight != $maxImageHeight
UNION ALL
SELECT 'heightEqual' AS COL1,COUNT(*) AS imgCount FROM (
SELECT imgHeight, imgWidth, imgId AS primaryId FROM primary_images
UNION ALL
SELECT imgHeight, imgWidth, primaryId FROM secondary_images
) AS union_table
WHERE primaryId = $imgId AND imgWidth != $maxImageWidth AND imgHeight = $maxImageHeight";
$equalDimensions_data = mysql_query($equalDimensions_query) or die('MySql Error' . mysql_error());
while ($row = mysql_fetch_assoc($equalDimensions_data)) {
$cnt[$row['COL1']] = $row['im开发者_如何学CgCount'];
}
var_dump($cnt);
(Notice I included var_dump($cnt)
as the last line)
The var_dump
returned the following array:
array
(
'allEqual' => string '2' (length=1)
'widthEqual' => string '0' (length=1)
'heightEqual' => string '0' (length=1)
)
I'm curious why the count is being returned as a string, and not as an integer?
Should it be returned as an integer? Or is it the norm when dealing with count queries, for the result to be returned as a string?
Thanks.
from http://www.php.net/manual/en/function.mysql-fetch-assoc.php:
Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
(emphasis mine) It's probably just easier for the MySQL driver to give you everything as a string, and assume you will know what to do with it. Just use intval() to get the integer value.
Everything is returned as a string¹, no matter if it's a column value (the column's type will not play any role) or the result of a function (the type of the return value will also not play a role).
¹when talking about the MySql driver, at least.
精彩评论