【问题标题】:Extract four records at a time from a database with php and bootstrap使用 php 和 bootstrap 从数据库中一次提取四条记录
【发布时间】:2016-07-25 20:25:01
【问题描述】:
我有一个数据库,我需要一次从中提取四条记录。
要提取所有记录,我使用此查询:
SELECT image FROM song ORDER BY date DESC
但我需要一次处理 4 条记录,因为在 HTML 中我每 4 张图像关闭一行。
echo"<div class='row'>";
while ($dati=mysqli_fetch_assoc($result))
{
echo"<a href='song.php'>";
echo"<div class='col-md-3'>";
echo"<img class='img-responsive' src='".$dati['immagine']."'><br>";
echo"</div>";
echo"</a>";
}
echo "</div><br>";
只要数据库中有未处理的记录,我需要每4条图像记录重新执行上面的命令。
【问题讨论】:
标签:
php
html
mysql
database
twitter-bootstrap
【解决方案1】:
LIMIT 4 但我建议您查询一次记录并在循环中添加一个计数器以了解何时有新行
【解决方案2】:
使用4的模块并显示您的格式
<?php
$counter=0;
$str="";
while ($dati=mysqli_fetch_assoc($result))
{
if($counter%4==0)
{
$str="<div class='row'>";
}
$str.="<a href='song.php'>";
$str.="<div class='col-md-3'>";
$str.="<img class='img-responsive' src='".$dati['immagine']."'><br>";
$str.="</div>";
$str.="</a>";
if($counter%4==0)
{
$str.="</div><br>";
}
$counter++;
}
echo $str;
?>
或者如果你不想像这样直接打印到字符串中
<?php
$counter=0;
while ($dati=mysqli_fetch_assoc($result))
{
if($counter%4==0)
{
echo "<div class='row'>";
}
echo "<a href='song.php'>";
echo "<div class='col-md-3'>";
echo "<img class='img-responsive' src='".$dati['immagine']."'><br>";
echo "</div>";
echo "</a>";
if($counter%4==0)
{
echo "</div><br>";
}
$counter++;
}
?>
【解决方案3】:
使用这个查询
SELECT image FROM song ORDER BY date DESC limit 4
【解决方案4】:
这将在执行 SELECT image FROM song ORDER BY date DESC 后使用引导程序在您的 html 中的每一行显示四个图像。
$num_rows = mysqli_num_rows($result);
for ($j = 0; $j < $num_rows; ++$j)
$dati[$j] = mysqli_fetch_assoc($result); //$dati is now a multidimensional array with an indexed array of rows, each containing an associative array of the columns
// You could alternatively use a for loop
// for($i=0; $i<$num_rows; $i++) insert while loop
$i=0;
while($i<$num_rows){ // start the loop to insert images in every row, 4 images per row
echo"<div class='row'>";
echo"<a href='song.php'>";
echo"<div class='col-md-3'>";
if($i<num_rows) // this prevents excessive rows from being displayed after $i reaches the number of rows
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>"; //post-increment $i
if($i<num_rows)
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>";
if($i<num_rows)
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>";
if($i<num_rows)
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>";
echo"</div>";
echo"</a>";
echo "</div><br>"
}