php - 来自数据库的 3 列动态表

标签 php mysql

我正在尝试创建一个具有 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..

最佳答案

我没有重建您的循环,因为我认为这不是 100% 的问题。您应该使用连接而不是 1,000 个查询,它更快并且通常可以解决问题。由于我不太确定您的数据库是如何设置的,因此通过 1 个查询您可以获得所有信息。

现在您可以使用 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);
}

关于php - 来自数据库的 3 列动态表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16264440/

相关文章:

php - Nix 可组合派生选项

mysql - 每三个月自动编辑查询 MySQL 的 WHERE 条件

mysql存储过程语法错误

php - 用户 'root' @'localhost' 的访问被拒绝(使用密码 : YES) after resetting root password

php - 多个 MySQL 表到 json_encode

javascript - 我如何使用 Jquery append() 显示数据

PHP 下载会阻止其余请求

mysql - Laravel Eloquent - undefined variable

php - 如何使用 PHP 更新 mysql 中的数据?

PHP 存储数组到数据库的逻辑问题