SELECT COUNT表示数据库中的列?

时间:2016-09-06 04:59:42

标签: php sql

如何计算表中与相关条件匹配的行数和计数的回显。

代码如下::

<?php 
     $sql = "SELECT * FROM input ORDER BY date DESC";
     $result = $conn->query($sql);

     if ($result->num_rows > 0) { 
     while($row = $result->fetch_assoc()) { 
     $myid = $row["id"] ;
 $sql3 = "SELECT COUNT question_id FROM output WHERE question_id = $myid";
    $result3 = $conn->query($sql3);
?>

<div id="q">

        <small><p><?php echo $row["date"]; ?></p></small>
        <p id="tag3"><small><?php echo $result3['']; ?></small></p>
</div>

任何建议都将受到赞赏..

3 个答案:

答案 0 :(得分:1)

您需要使用COUNT(question_id)函数,如下所示

    $sql3 = "SELECT COUNT(question_id ) as  TotalQuestions FROM output WHERE question_id = $myid";
 $result3 = $conn->query($sql3);

然后使用fetch_fieled()

从上面的查询中获取结果
while ($info = $result3->fetch_field()) {
$TotalCount = $info->TotalQuestions ;
}

然后显示值

<small><?php echo $TotalCount ; ?></small

答案 1 :(得分:1)

引用缺失

$sql3 = "SELECT * question_id FROM output WHERE question_id = '".$myid."'";

其次我看不到关闭括号

<?php 
     $sql = "SELECT * FROM input ORDER BY date DESC";
     $result = $conn->query($sql);

     if ($result->num_rows > 0) { 
     while($row = $result->fetch_assoc()) { 
     $myid = $row["id"] ;
$sql3 = "SELECT COUNT(*) as rowCount FROM output WHERE question_id = '".$myid."'";
    $result3 = $conn->query($sql3);
$rowCount= $result3->fetch_assoc();
?>

<div id="q">

        <small><p><?php echo $row["date"]; ?></p></small>
        <p id="tag3"><small><?php echo $rowCount['rowCount']; ?></small></p>
</div>
<?php }//while

} //if 

?>

答案 2 :(得分:1)

试试这个

 $sql3 = "SELECT COUNT(1) as row_count FROM output WHERE question_id = ".$myid."";
 $result3 = $conn->query($sql3);
 $row_count = $result3->fetch_assoc();

 echo $row_count['row_count'];