开发者

Using PHP foreach to get mysql table data

开发者 https://www.devze.com 2023-02-10 19:07 出处:网络
ive got 1 database table contains row: TABLE FROM reservations: attandee01 attandee02 attandee03 attandee04

ive got 1 database table contains row:

TABLE FROM reservations:

attandee01  
attandee02  
attandee03  
attandee04  
attandee05  
attandee06

PHP CODE:

$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");

while($r = $q->fetch_array(MYSQLI_ASSOC)):
   echo '<td>' .开发者_开发知识库 $r['attandee1'] . '</td>';
   echo '<td>' . $r['attandee2'] . '</td>'
   echo '<td>' . $r['attandee3'] . '</td>'
endwhile;

or is there any simple way using foreach to echo attandee1 - attandee10?


$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");

while($r = $q->fetch_array(MYSQLI_ASSOC)):
   foreach($r as $value) {
       echo '<td>' . $value . '</td>';
   }
endwhile;

Should echo each column value per table row.

EDIT: If you only want the attendees:

$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");

while($r = $q->fetch_array(MYSQLI_ASSOC)):
   for($i = 1; $i < 11 $i++) {
       echo '<td>' . $r['attendee'.$i] . '</td>';
   }
endwhile;


you can use foreach, of course, as $r is a regular array and can be iterated using foreach() operator. Did you try it?

However, looking at the field names, I suspect serious design flaw in your data structure.
It seems attandees should be stored in another table.

You may also consider using templates. Printing data directly from the database loop is very bad practice. You have to get all your data first and only then start printing it out.


Well yes:

for($i=1; $i<11; ++$i) {
  echo "<td>".$r["attandee".$i]. "</td>";
}

But that is columns, what you want is the row based solution for that I'd use something like:

for($r=$q->fetch_assoc(); !is_null($r); $r= $q->fetch_assoc()) {
   echo "<td>".array_pop($r)."</td>"; // output the only element in the array?
}
$q->free(); // don't forget to free the memory of the result set!


don't know if i understood your question... is this what you're looking for:

while($row = $q->fetch_array(MYSQLI_ASSOC)):
    foreach($row as $field){
       echo '<td>' . $field . '</td>';
    }
endwhile;


Not really sure if this is what you are looking for, but give it a shot:

while($r = $q->fetch_array(MYSQLI_ASSOC)) {
   foreach($r as $value) {
      echo '<td>' . $value . '</td>';
   }
}


As example you can use alternate syntax.

<table>
<?php foreach ($mysqli->query($sql) as $row ): ?>
<tr><td><?php echo $row['row_name1']; ?></td><td><?php echo $row['row_name2']; ?></td></tr>
<?php endforeach; ?> 
</table>
0

精彩评论

暂无评论...
验证码 换一张
取 消