简体   繁体   中英

display only 3 foreach result per row

i have script as follows

$output="<table class='products'><tr>"; 
while($info = mysql_fetch_array( $data )) { 
    //Outputs the image and other data
    $output.= "<td>
    <img src=http://localhost/zack/sqlphotostore/images/"   .$info['photo'] ." width=323px ></img> 
    <b>Name:</b> ".$info['name'] . "
    <b>Email:</b> ".$info['email'] . " 
    <b>Phone:</b> ".$info['phone'] . "</td> "; 
}
$output.="<tr></table>";
print $output;
?>

it shows all results in long horizontal line how do i break the results so that they show in new row after 3 count.

Keep a counter, and output a new table row every 3 images

$output="<table class='products'>"; 

$counter = 0;
while($info = mysql_fetch_array( $data )) 
{  
    if( $counter % 3 == 0 )
        $output .= '<tr>';

    $output .= "<td>";
    $output .= "<img src=http://localhost/zack/sqlphotostore/images/".$info['photo'] ." width=323px ></img>";
    $output .= "<b>Name:</b> ".$info['name'];
    $output .= "<b>Email:</b> ".$info['email'];
    $output .= "<b>Phone:</b> ".$info['phone']."</td> ";

    if( $counter % 3 == 0)
         $output .= "</tr>";

    $counter++;
}
$output.="</table>";
print $output;
?>

Add a counter and start a new row every time it reaches a multiple of 3.

$counter = 0;
while($info = mysql_fetch_array($data)) {
   if ($counter++ % 3 == 0) {
       if ($counter > 0) {
           $output .= "</tr>";
       }
       $output .= "<tr>";
   }
   // stuff
}
if ($counter > 0) {
    $output .= "</tr>";
}

$output .= "</table>";

Please note: It may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM