user6779766 user6779766 - 3 months ago 7
PHP Question

SELECT COUNT for column in database?

How to Count number of rows in a table that matches to the related condition and echo that count out.

Code goes as follows::

<?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>


Any Suggestions will be appreciated..

Answer

Quotes missing

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

Secondly i dont see closing braces for while

<?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 

?>