2016-07-25 72 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>" 
} 
相關問題