简体   繁体   中英

Iterating through column values for multiple rows mysqli

I have a table with 4 values, 3 of which I am interested in. The MYSQL query I am using is:

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

I have tested this query and it works with my database. I can figure out how to get single columns to return values, but I cannot figure out multiple columns. I have tried a variety of for loops, using an array to store the various column names and iterating things. I'm getting very frustrated, and am not sure what to do.

This was my last attempt:

$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>";

Obviously I'm trying to build it into a string of code so I can echo it later into the page where I need it. Every time I run this page, though, I get nothing but a blank page with no source code.

Lose the foreach and use $row , not $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>";
}

I think your problem is that you dont close your while loop ,also your foreach is not correct ,this is how it should be even if it's not necessary :

 $tablebuild .= "<table>";
while ( $row = $result->fetch_assoc() ){

   $tablebuild .= "<tr>";

   foreach ($row as $next){
      $tablebuild .= "<td>$next<td>";
   }

   $tablebuild .= "</tr>";

}

 $tablebuild .= "</table>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM