【问题标题】:Get Count For A Set Of Fetched Field Values - MySQL / PHP获取一组获取的字段值的计数 - MySQL / PHP
【发布时间】: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 来说应该不是问题

标签: php mysql count fetch


【解决方案1】:

在您的while 循环之前定义一个变量$count_images = 0,并在循环内每次有一个$row['filename'] 不是NULL 或空字符串时将变量增加+1。

while 循环之后你可以echo $count_images:

<?php
    $stmt = $connection->prepare("SELECT * FROM imageposts WHERE username = :username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();   

     $count_images = 0;  // AT THE BEGINNING THERE ARE 0 IMAGES

    while ($row = $stmt->fetch()) {   // LOOP START

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

    if ($db_image_filename != NULL  && $db_image_filename != '') {
         $count_images++;  // IF IMAGE FOUND, INCREASE BY +1
    }

?>
<figure>

   <!-- html is outputted here including values using the PHP variables above -->

</figure>
<?php } // END OF WHILE LOOP ?>

<p>Number of images: <?php echo $count_images; ?></p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    相关资源
    最近更新 更多