Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL Count Query Result is String, Not Integer

Tags:

sql

php

mysql

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['imgCount']; 
}

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.

like image 677
stefmikhail Avatar asked Feb 22 '23 22:02

stefmikhail


2 Answers

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.

like image 137
evan Avatar answered Feb 25 '23 11:02

evan


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.

like image 25
Jon Avatar answered Feb 25 '23 12:02

Jon