Search code examples
phpmysqlforeachmysql-num-rows

Foreach inside While Statement (NumRows)


I'm trying to figure out how I would do a foreach statement inside my while statement. As you can tell by this code, it will only submit 1 row out of the table, even though it selects all the rows. How would I make it select each row?

Code:

$q2 = mysql_fetch_array(mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'"));
$num_rows = mysql_num_rows($q2);
while(count($num_rows) > $i){
    echo "<div style='float:left;width:940px;margin-bottom:2%;margin-left:".($i + 1)."0px;margin-right:25%;'><div style='margin-left:".($i + 1)."0px;border:1px solid #cecece;padding:10px;'>Posted By: <a href='#'>".user2($q2[1])."</a><h2>".$q2[2]."</h2></div></div></div>";
    $i++;
}

New Attempt:

$q2 = mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'");
$i = 0;
foreach($q2 as $s){
    echo "<div style='float:left;width:100%;margin-bottom:2%;margin-left:".($i + 1)."0px;margin-right:25%;'><div style='margin-left:".($i + 1)."0px;border:1px solid #cecece;padding:10px;'>Posted By: <a href='#'>".user2($s[1])."</a><h2>".$s[2]."</h2></div></div></div>";
    $i++;
}

Although now this doesn't display any rows.


Solution

  • $q2 = mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'");
    
    $i = 0;
    while ($s = mysql_fetch_array($q2, MYSQL_NUM)) {
        echo "<div style='float:left;width:100%;margin-bottom:2%;margin-left:".($i + 1)."0px;margin-right:25%;'><div style='margin-left:".($i + 1)."0px;border:1px solid #cecece;padding:10px;'>Posted By: <a href='#'>".user2($s[1])."</a><h2>".$s[2]."</h2></div>   </div></div>";
        $i++
    }