I was wondering how would go about displaying five images in a row using lists. For example, how would I generate the following XHTML code below using PHP & MySQL?
Here is the XHTML code.
<ul>
<li><a href="#" title=""><img src="" /></a></li>
<li><a href="#" title=""><img src="" /></a></li>
<li><a href="#" title=""><img src="" /></a></li>
<li><a href="#" title=""><img src="" /></a></li>
<li><a href="#" title=""><img src="" /></a></li>
</ul>
<ul>
<li><a href="#" title=""><img src="" /></a></li>
开发者_StackOverflow <li><a href="#" title=""><img src="" /></a></li>
<li><a href="#" title=""><img src="" /></a></li>
<li><a href="#" title=""><img src="" /></a></li>
<li><a href="#" title=""><img src="" /></a></li>
</ul>
Here is my PHP & MySQL code so far.
$url = array();
$title = array();
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
GROUP BY images.id");
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
$url[] = $row["url"];
$title[] = $row["title"];
}
}
just echo it out it your while loop: EDIT: noticed your example has a new ul every 5 images, code has been adjusted to handle that.
if (!$dbc) {
print mysqli_error($mysqli);
} else {
$rowCount = 0;
while($row = mysqli_fetch_array($dbc)){
if($rowCount % 5 == 0){
echo "<ul>";
}
echo "<li><a href='" .$row["url"]. "' title='".$row['title']."'>";
echo "<img src='".$row['src']."'></a></li>";
if($rowCount % 5 == 4) {
echo "</ul>";
}
$rowCount++;
}
}
you've got it perfect! now you have just to add an HTML part. Though, separate arrays is not good, it would be better to use a single one
$DATA = array();
while($row = mysqli_fetch_array($dbc)){
$DATA[] = $row;
}
and then you're going to print out HTML
<ul>
<? foreach ($DATA as $row): ?>
<li><a href="<?=$row['url']?>" title="<?=$row['title']?>"><img src="" /></a></li>
<? endforeach ?>
</ul>
though if you need to split your lists into smaller parts, you will need another code
there are many ways to do it. the easiest one is to add some markers to array.
and than use it at the template:
<? foreach ($DATA as $row): ?>
<? if($row['ul']): ?><ul><? endif ?>
<li><a href="<?=$row['url']?>" title="<?=$row['title']?>"><img src="" /></a></li>
<? if($row['/ul']): ?></ul><? endif ?>
<? endforeach ?>
The easiest way to do this without having lots of crazy statements to determine when to split the list is to take advantage of array_chunk
:
<?php
$url = array();
$title = array();
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
GROUP BY images.id");
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
$rows = $row;
}
}
$row_groups = array_chunk($rows, 5);
foreach($row_groups as $row_group ) {
echo "<ul>";
foreach( $row_group as $row ) {
?>
<li><a href="<?=$row['url'] ?>" title="<?=$row['title'] ?>"><img src="<?=$row['url'] ?>"/></a></li>';
<?php
}
echo "</ul>";
}
?>
精彩评论