【发布时间】:2021-11-07 21:26:41
【问题描述】:
我有一些从 MySQL 数据库返回的数据,这些数据输出特定用户的帖子详细信息。
我想输出图像数量的计数(下面用 $db_image_filename 值表示)。
如何计算列中字段值的数量?我以为我可以使用 PHP 的 count() 函数,但这不起作用?
有没有办法在 PHP 中做到这一点,而无需在数据库上运行另一个查询(因为该数据已经从数据库中获取,我只需要它的计数值)?然后,该值将在下面示例底部的<p> 标记中回显。
<?php
$stmt = $connection->prepare("SELECT * FROM imageposts WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetch()) {
$db_image_id = htmlspecialchars($row['image_id']);
$db_image_title = htmlspecialchars($row['image_title']);
$db_image_tags = htmlspecialchars($row['image_tags']);
$db_image_filename = htmlspecialchars($row['filename']);
?>
<figure>
<!-- html is outputted here including values using the PHP variables above -->
</figure>
<p>Number of images: <?php // echo the count value of $db_image_filename ?></p>
<?php } ?>
【问题讨论】:
-
count()仅适用于实现Countable的数组或对象。你可以使用PDOStatement::rowCount()。 -
这能回答你的问题吗? Row count with PDO
-
@Sherif 文档建议不要将其用于 SELECT 语句:
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications. -
这对你的 AFAIC 来说应该不是问题