开发者

mysqli returns simple query as object - why?

开发者 https://www.devze.com 2023-03-28 18:40 出处:网络
I\'m having a simple problem understanding how to parse stdObject returns from simple queries with mysqli ... I\'ve tried a couple of different ways to turn the stdObject into an array and also just u

I'm having a simple problem understanding how to parse stdObject returns from simple queries with mysqli ... I've tried a couple of different ways to turn the stdObject into an array and also just using fetch_object() like here:

$cart_q = "SELECT card_name FROM products WHERE product_cat = 'HPC' LIMIT 12";
$result = $mysqli->query($cart_q);

echo "<table>";
$i = 0;
while ($products = $result->fetch_object()) {
   if($i == 0)
      echo "<tr>";
      echo "<td>". $products->card_name ."</td>";
      $i++;
      if($i == 3) {
e开发者_开发问答cho "</tr>";
$i=0;
     }
 }
 echo "<table>"; 

I've done a print_r of the object and gotten an associative array, but breaking it down to dislay within a page has yet to work ... any ideas?


Note: I actually think your problem is with iterating over the result array, thus label should be php, or /and HTML, but let's see:

Its usually good to separate retriving records from presentation, for example like this:

$mysqli = new MySQLi($db_host, $db_user, $db_pass, $db_name);
$cart_q = "SELECT card_name FROM products WHERE product_cat = 'HPC' LIMIT 12";
$result = $mysqli->query($cart_q) or die($mysqli->error);

$card_names = array();
while ( $row = $result->fetch_assoc() ){
    $card_names[] = $row['card_name'];
}

Above will create array $card_names => array('card_name1', 'card_name2' ... etc)

Now, you can use foreach to iterate over that array and create output HTML. From what I've understood you want to create HTML table with 4 cells per row and one card name per cell.

echo '<table><tr>';

$i = 1;
foreach ( $card_names as $name ){
    echo "<td>$name</td>";

    if ( $i % 4 == 0) echo '</tr><tr>';

    $i++;
}
($i - 1) % 4 == 0 ? echo '</tr></table>'; : echo '</table>';
0

精彩评论

暂无评论...
验证码 换一张
取 消