php - 计算一个数据库字段中的项目数

标签 php mysql count

我的 MySQL 数据库中有一个名为 Sponsors 的表。
该表有两个字段。 事件名称names 字段填充了不同的词。例如 Pieter, Sam, Thomas。我想计算 names 中名字的数量。

我如何使用 PHP 和 SQL 请求执行此操作。我虽然是这样的……

$query = mysql_result(mysql_query("SELECT names FROM Sponsors WHERE id = '55'"));
$result = str_replace(',',' ', $query);
$total = count($result);

但这并没有解决...

编辑

if(!empty($activiteiten))
    {
        foreach($activiteiten as $k => $v) 
            {
                $query = mysql_result(mysql_query('SELECT aanwezig FROM tblLeidingAgenda WHERE id = "'.$v["id"].'"),0');
                $result = str_replace(", ", " ", $query);
                $total = str_word_count($result);

                echo '<div class="lof-main-item">';
                echo '<img src="images/791902news3.jpg" title="Newsflash 2" height="300" width="900">           
                            <div class="lof-main-item-desc">
                                <h3><a target="_parent" title="Newsflash 2" href="#">'.$v["uur"].'</a></h3>
                        <p>'.$v["titel"].'</p>
                        ID: '.$v["id"].'
                    <form method="post" action="#">
                        <input type="submit" name="aanwezig" value="Ik ben aanwezig"/><br />
                        <input type="submit" name="afwezig" value="Ik ben afwezig"/><br />
                        <input type="submit" name="herinnering" value="Stuur herinnering"/><br />
                        <input type="text" name="id" value="'.$v["id"].'" />
                        Ik ben aanwezig ('.$total.'): '.$v["aanwezig"].'<br />
                        Ik ben afwezig: '.$v["afwezig"].'</form></div></div> ';
            }
    }

最佳答案

检查行数:

$total = mysql_num_rows($result);

PHP Manual (mysql_num_rows)

或者 SELECT COUNT(*) 首先。

编辑

没关系,看起来您正在单个单元格中存储逗号分隔的列表。顺便说一句,这是一个不好的做法。您可能只需要另一个 MySQL 表来正确存储它们。如果您决定不修复数据库架构,尽管这对您有用:

$query = mysql_result(mysql_query("SELECT names FROM Sponsors WHERE id = '55'"));
$result = explode(',',$query);
$total = count($result);

PHP Manual (explode)

关于php - 计算一个数据库字段中的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7197738/

相关文章:

mysql - 如何修复 InnoDB 损坏的数据结构?

php - 拉拉维尔 : Fetch record from db and send it to email template

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows等…期望参数1为资源或结果

没有数字键的PHP array_push

MySQL - 显示 SELECT 中的出现次数(计数)

mysql - 如何从mysql表中选择范围计数?

mysql - 连接 3 个表,统计一张表中最高的用户数

php - 清理或验证电子邮件 php

php - 从下面的php+mysql表代码中显示总计

php - ORDER MySQL 结果按日期并使用 LIKE