2016-07-25 73 views
0

我有一个数据库,我需要一次从他们四个记录中提取。从一个数据库一次提取四个记录与PHP和引导

提取所有记录,我用这个查询:

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个图像记录上重新执行命令。

+0

可能重复的[php while循环变量为每第三个div](http://stackoverflow.com/questions/1806582/php-while-loop-variable-for-every-third-div) – Epodax

回答

0

使用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++; 
} 

?> 
1

LIMIT 4但我会建议您一旦查询的记录,并在循环添加计数器要知道,当你有一个新的行

0

使用此查询

SELECT image FROM song ORDER BY date DESC limit 4 
0

执行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>" 
} 
相关问题