php - 遍历多行 mysqli 的列值

标签 php database mysqli

我有一个包含 4 个值的表,其中 3 个我感兴趣。我使用的 MYSQL 查询是:

Select Product.product_id, Product.cost, Product.image from Product

我已经测试了这个查询,它适用于我的数据库。我可以弄清楚如何让单列返回值,但我无法弄清楚多列。我尝试了各种 for 循环,使用数组来存储各种列名并迭代事物。我感到非常沮丧,不知道该怎么办。

这是我最后一次尝试:

$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or 
        die('There was a problem connecting to the database');


$stmt = "Select Product.product_id, Product.cost, Product.image from Product";

if(!$result = $conn->query($stmt)){ 
die('there was an error retrieving the information');
}

$tablebuild = "<table>";

while ( $row = $result->fetch_assoc() ){

foreach ($row as $next){
    $tablebuild .= "<tr><td>";
    $tablebuild .= $result['product_id'];
    $tablebuild .= "</td><td>";
    $tablebuild .= $result['cost'];
    $tablebuild .= "</td><td>";
    $tablebuild .= $result['image'];
    $tablebuild .= "</td></tr>";
}

$tablebuild .= "</table>";

显然,我正在尝试将其构建为一串代码,以便稍后可以将其回显到我需要它的页面中。但是,每次我运行此页面时,除了没有源代码的空白页面外,我什么也得不到。

最佳答案

去掉foreach,使用$row,而不是$result

while ( $row = $result->fetch_assoc() ){
    $tablebuild .= "<tr><td>";
    $tablebuild .= $row['product_id'];
    $tablebuild .= "</td><td>";
    $tablebuild .= $row['cost'];
    $tablebuild .= "</td><td>";
    $tablebuild .= $row['image'];
    $tablebuild .= "</td></tr>";
}

关于php - 遍历多行 mysqli 的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18564494/

相关文章:

php - 如果语句对象未设置,是否需要调用 PDOStatement::closeCursor() ?

php - 您如何访问简单的 DOM 选择器?

php - 如何从三四张表中随机抽取问题而不出现重复问题

php - 升级到 PHP 5.6,无法建立 MySQL 连接

php - 如何将请求路由到文档根目录外的 codeigniter 项目

php - 如何通过IP地址获取国家代码和货币代码?

SQL连接2个有日期差异的表

database - Solr "real time"索引

php - MySQL lower_case_table_names 导致 PHP 连接错误

php - Mysqli 最后插入 id 不起作用