thexpressive thexpressive - 2 months ago 9x
MySQL Question

PHP incomplete result table from sql query

I am new to web development and starting learning about CRUD.

My question is that while I successfully show the table listing 3 product on 1 row, that on the second row the product no 4 are missing and skipping to the product no 5 and keep missing every last 3 row.

function getData(){
global $connect;
$query = "SELECT id, name, category, price, image, info FROM product_data";
$results = mysqli_query($connect, $query) or die(mysql_error());
echo "<table border = 0 >";
echo "<tr class='homepagetable'>";
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
$x = $x + 1;
echo "<td class='homepagetable'>";
echo "<a href=itemdetails.php?id=$id>";
echo '<img src=img/' . $image . ' style="max-width:220px;max-height:240px;width:220px;height:240px;"></img><br/>';
echo '<div class="truncate">'. $name .'</div><br/>';
echo "</a>";
echo 'Rp.'.$price .'<br/>';
echo "</td>";
} else {
echo "</tr><tr>";
echo "</table>";

Thanks in advance!


Your problem is that you have a wrong condition here:

if($x <=3)... else{...}

Change the if/else to this:

if($x <3){$x++;}

// something

if($x == 3){
 $x = 1;
 //Close and open tr

And you need to close the <img> tag, and the last <tr> tag outside of the loop