Nurul Watoni Nurul Watoni - 5 months ago 8
SQL Question

Print data fetched from mysql database

<?php

$koneksi = mysqli_connect('mysql.idhostinger.com','root','pw','db');
$result = mysqli_query($koneksi,'select * from posting');

while($row = mysqli_fetch_row($result)) {

for($x = 0; $x <= count($row); $x++) {
echo "<div style='background:green'>$row[$x]</div>";
}
}
?>


Hello guys! This code takes data from mysql, then prints it in a div container, wrapped with a div too.

The problem is that every row of data captured produces 2 div.

How to get each row to produce only and only 1 div?

Thank you.

Answer

You're creating a div for each item in each row:

while($row = mysqli_fetch_row($result))  {
    for($x=0;$x<=count($row);$x++){
        echo "<div style='background:green'>$row[$x]</div>";
    }
}

If you want a single div for the "row" and to put all items in that div, put the div in the loop that iterates over the rows:

while($row = mysqli_fetch_row($result))  {
    echo "<div style='background:green'>";
    for($x=0;$x<=count($row);$x++){
        echo $row[$x];
    }
    echo "</div>";
}