2014-10-01 53 views
-1

我已經構建了一個SQL查詢來佈置一些網頁上的信息。查詢運作良好。問題是與while循環CSS類必須是自動遞增每次迭代由1需要想法正確的HTML呈現與PHP

<div class="related-item item1"> 

「物品1」應該成爲「ITEM2」在接下來的迭代等等。你能給我一些想法如何去做嗎?

<?php 
    //Construct the SQL query code 
    $rel = "SELECT entries.*, images.name 
      FROM entries, images 
      WHERE entries.id = blog_id 
      ORDER BY dateposted DESC 
      LIMIT 0, 3;"; 
    //Send the query to the MySQL server 
    $result = mysql_query($rel); 

    //Pull the row as an associative array 
    while ($row = mysql_fetch_assoc($result)) { 

    echo '<div class="related-item item1"> 
      <div class="thumbnail-wrapper">'; 
    echo  '<a href="#"><img src="./images/' . $row['name'] . '" alt="How SHAPE Reader Caitlin Flora Lost 182 Pounds"/></a></div> 
    <h4 class="related-article-title"> 
     <a href="#">' . $row['subject'] . '</a> 
    </h4> 
    </div>'; 
    } //End of while loop 

    ?> 
+0

請,或不使用新代碼'mysql_ *'功能(http://stackoverflow.com/questions/12859942/why-不應該-I-使用MySQL的函數式的PHP)。 *他們不再維護,並[已正式棄用](https://wiki.php.net/rfc/mysql_deprecation)*。看到[紅色框](http://uk.php.net/manual/en/function.mysql-connect.php)?學習[準備的語句](http://en.wikipedia.org/wiki/Prepared_statement),並使用[PDO](http://us1.php.net/pdo)或[MySQLi](http:// us1.php.net/mysqli)。 [這篇文章](http://php.net/manual/en/mysqlinfo.api.choosing.php)將幫助你決定哪些。 – 2014-10-01 19:52:32

回答

3

只要保持計數器變量會

$cnt = 1; 
while(fetch from db) { 
    echo "<a class='foo{$cnt}'>click me</a>"; 
    $cnt++; 
} 

產生

<a class='foo1'>click me</a> 
<a class='foo2'>click me</a> 
<a class='foo3'>click me</a> 
etc... 

但一般這樣的事情是沒有必要的CSS。您必須爲創建的這些元素中的每一個創建一條css規則,這些元素會變得難以置信地變得醜陋和重複。在CSS中有nth-child的支持,所以你可以根據子元素是哪個子元素(1st,2nd,... Nth)來編寫「修改」自己的規則。

+0

謝謝你的建議。 – Anay 2014-10-01 20:57:16

0

添加一個整數,並增加它...

<?php 
    //Construct the SQL query code 
    $rel = "SELECT entries.*, images.name 
      FROM entries, images 
      WHERE entries.id = blog_id 
      ORDER BY dateposted DESC 
      LIMIT 0, 3;"; 
    //Send the query to the MySQL server 
    $result = mysql_query($rel); 

$i = 1; 
    //Pull the row as an associative array 
    while ($row = mysql_fetch_assoc($result)) { 

    echo '<div class="related-item item{$i}"> 
      <div class="thumbnail-wrapper">'; 
    echo  '<a href="#"><img src="./images/' . $row['name'] . '" alt="How SHAPE Reader Caitlin Flora Lost 182 Pounds"/></a></div> 
    <h4 class="related-article-title"> 
     <a href="#">' . $row['subject'] . '</a> 
    </h4> 
    </div>'; 
    $i++; 
    } //End of while loop 

    ?> 
+0

感謝您的意見。 – Anay 2014-10-01 20:57:44