2012-08-23 81 views
-1
<? 

$sql = dbquery("SELECT `id`, `title`, `description` FROM `content` LIMIT 0,12 "); 
while ($row = mysql_fetch_array($sql)) { 
    $id   = $row["id"]; 
    $title  = $row["title"]; 
    $description = $row["description"]; 
    $content  = ' 
    <div class="description-box"> 
    <p>page id: ' . $id . '</p> 
    <p>' . $title . '</p> 
    <p>' . $description . '</p> 
    </div>'; 
} 

echo $content; 
?> 

//聲明:DIV CLASS = 「描述盒」我該如何解決這個PHP的MySQL循環?

//我怎麼能替換成:DIV CLASS = 「描述盒nopadding」 每3周輸出的div後? HTML的

例生成的代碼:

<div class="description-box nopadding"> 
// content 
</div> 
<div class="description-box"> 
// content 
</div> 
<div class="description-box"> 
// content 
</div> 
<div class="description-box"> 
// content 
</div> 

//然後再分度nopadding

+4

使用計數器變量,由3每次的循環是時間把它和如果整數除法的其餘部分是0 - 你有「每隔3次」迭代。 –

+5

它可能無助於回答你的問題,但你應該停止使用'mysql_ *'函數。他們正在被棄用。請使用[PDO](http://php.net/manual/en/book.pdo.php)(自PHP 5.1起支持)或[mysqli](http://php.net/manual/en/book)。 mysqli.php)(自PHP 4.1起支持)。如果你不確定使用哪一個,[閱讀本文](http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/)。 – Matt

+2

你也應該避免使用像這樣的短開標籤('')。 ''不是很多額外的工作,即使你必須在頁面上輸入10次,它也可以確保你的服務器支持代碼。 ''是一個不同的故事,無論您的服務器上是否啓用了'short_open_tags',它仍然有效(從PHP 5.4開始)。 – Matt

回答

5
<div class="description-box'.(($c++%3==0)?' nopadding':'').'"> 

記得初始化$c

這很簡單:

如果剩餘除法$c 3等於0 ' nopadding'的字符串,否則添加'' stirng

0 % 3 == 0 // add 
1 % 3 == 1 
2 % 3 == 2 
3 % 3 == 0 // add 
4 % 3 == 1 
... 

語法:

echo true ? "it's true" : "it's false"; // it's true 
echo (5 % 3); // 2, remainder of 5/3 division 
$c = 0; 
echo $c++; // 0 
echo $c; // 1 
+0

由於您發佈了較短的代碼,因此您應該說明它的作用,以及爲什麼選擇短版而不是長版。 –

+0

@ N.B。這裏你去 – Peter

+0

這不工作得很好...它返回兩個'description-box'然後一個'description-box nopadding'然後另外兩個'description-box'等等...... – m3tsys

0
<? 
$sql = dbquery("SELECT `id`, `title`, `description` FROM `content` LIMIT 0,12 "); 
$counter = 0; 
while($row = mysql_fetch_array($sql)){ 
$id = $row["id"]; 
$title = $row["title"]; 
$description = $row["description"]; 
if($counter%3 == 0) 
{ 
$div = '<div class="description-box nopadding">' 
} 
else 
{ 
$div = '<div class="description-box">'; 
} 
content = $div.' 
<p>page id: '.$id.'</p> 
<p>'.$title.'</p> 
<p>'.$description.'</p> 
</div>'; 
$counter++; 
} 

echo $content; ?> 
+0

這只是錯誤的。你怎麼能把'if'語句放在字符串中? – Peter

+0

Didnt看到字符串..相應地調整。 – Shawn

+0

經過三次編輯,它仍然是錯誤的。 'content ='$ div'應該是'$ content = $ div.''和'$ counter'應該從'0'開始 – Peter