一尘不染

PHP MySQL计数查询结果为字符串,而不是整数

sql

我有以下MySQL查询和PHP代码,用于将Count结果格式化为单个数组:

$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);

(注意,我var_dump($cnt)作为最后一行包括在内)

var_dump返回以下数组:

array
(
  'allEqual' => string '2' (length=1)
  'widthEqual' => string '0' (length=1)
  'heightEqual' => string '0' (length=1)
)

我很好奇为什么计数以字符串形式而不是整数形式返回?

应该以整数形式返回吗?还是在处理计数查询时将结果作为字符串返回,这是正常的做法吗?

谢谢。


阅读 115

收藏
2021-05-23

共1个答案

一尘不染

http://www.php.net/manual/en/function.mysql-fetch-
assoc.php:

返回与提取的行相对应 的字符串关联数组, 如果没有更多行,则返回FALSE。

(强调我的意思)对于MySQL驱动程序来说,将所有内容作为字符串提供给您,并假设您将知道如何处理它,可能会更容易些。只需使用intval()即可获取整数值。

2021-05-23