因此,当列值是MySQL函数调用的返回值时,作为普通的PHP查询返回一个数组,我从未向我解释过如何从查询的结果集数组中实际提取值。
$countThemes = Singlequery(
'SELECT COUNT(1) FROM items WHERE type = :type',
array(':type' => 'theme'),
$conn
);
这是我的查询,它返回;
Array
(
[0] => Array
(
[COUNT(1)] => 5
)
)
我需要值5
。到目前为止,我已经在下面设置了它,但我不确定该调用什么,因为我不能像普通的Select *
查询那样调用列名。
<?php foreach ($countThemes as $countTheme) : ?>
<a href="#" class="btn view-all">View All <?= $countTheme['name']; ?></a>
<?php endforeach; ?>
使用别名返回COUNT
函数:
$countThemes = Singlequery('SELECT COUNT(1) AS num_items FROM items WHERE type = :type',
array(':type' => 'theme'), $conn);
然后,您的数组应该具有索引num_items
,而不是COUNT(1)
。
这也会起作用:
echo $result[0]['COUNT(1)'];
然而,在我看来,在SQL查询中使用别名(正如nickb所建议的那样)更为优雅。