2013-04-28 101 views
1

我想創建一個3列寬的動態表。輸入自動從數據庫收集。從數據庫動態3列表

的代碼,我有:

$var_product_list = mysql_query("SELECT c.link AS clink,s.section_id,s.link AS slink,s.name AS sname FROM category c,section s WHERE c.link='$_GET[category]' AND s.category_id=c.category_id ORDER BY s.name ASC", $db); 
    while($row_product_list = mysql_fetch_array($var_product_list)) 
    { 
     $nbCols = 3; 
     $nbRows = count($row_product_list['section_id'])/$nbCols; 
     for($row=0; $row<$nbRows; $row++) { 
      array_push($arr_product_list, "<tr>"); 
      for($i=0; $i<$nbCols; $i++) { 
       $var_product_count = mysql_query("SELECT COUNT(prod_id) FROM products WHERE section_id='$row_product_list[section_id]' GROUP BY section_id", $db); 
       $row_product_count = mysql_fetch_array($var_product_count); 
       $nr_of_products = $row_product_count['COUNT(prod_id)']; 
       if(empty($nr_of_products)){$nr_of_products = 0;} 

       $index = $indexes[$row + ($i*$nbRows)]; 
       array_push($arr_product_list, "<td><a href=\"$bswConfig_live_site/browse/$row_product_list[clink]/$row_product_list[slink]\">$row_product_list[sname]</a> ($nr_of_products)</td>"); 
      } 
      array_push($arr_product_list, "</tr>"); 
     } 
    } 

當我得到的輸出,它的複製在每一行的3倍。

例子:

Other | Other | Other 
House | House | House 
Garage| Garage| Garage 

相反的:

Other | House | Garage 
Item4 | Item5 | etc.. 
+1

不錯[SQL注入攻擊](http://bobby-tables.com)漏洞。享受你的服務器pwn3d。 – 2013-04-28 15:29:51

+0

XSS也是可能的;將數據輸出到網頁時使用'htmlspecialchars'。 – 2013-04-28 15:33:14

+1

[請不要使用mysql_ *函數](在新代碼中)(http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。他們不再被維護[並被正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。看到[紅色框](http://uk.php.net/manual/en/function.mysql-connect.php)?瞭解[_prepared statements_](http://en.wikipedia.org/wiki/Prepared_statement),並使用[PDO](http://php.net/pdo)或[MySQLi](http:// php。 net/mysqli) - [這篇文章](http://php.net/manual/en/mysqlinfo.api.choosing.php)將幫助你決定哪個。 – TNK 2013-04-28 15:39:18

回答

1

我沒有重建你的循環,因爲我不認爲它是100%的問題。您應該使用連接而不是1,000個查詢,速度更快,通常可以解決問題。由於我不太確定你的數據庫是如何設置的,只要有一個查詢,你就可以獲得你的所有信息。

現在你可以使用PHP來建立你的行,我不知道這些數據是如何回來真正建立一個表。

在不相干的筆記上,您應該使用PDO或Mysqli,不推薦使用mysql。

<?php 

$cat = mysql_real_escape_string($_GET["category"]); 
$prods = mysql_query(" 
    SELECT c.link AS clink,s.section_id,s.link AS slink,s.name AS sname, count(s.prod_id) prod_count 
    FROM category c 
    INNER JOIN section s ON s.category_id = c.category_id 
    INNER JOIN products p ON s.section_id = p.section_id 
    WHERE c.link='$cat' 
    group by s.section_id 
    ORDER BY s.name ASC", $db); 
while($row = mysql_fetch_array($prods)){ 
    print_r($row); 
}