Miuranga
Miuranga

Reputation: 2463

Check the table row and column number with database give row id and column id in PHP

In my project I have print fixed 10*10 table using two for loops. My database have two fields for row_id and column_id. I want to check if database given row id and column id is same to the table row number and column number print some string. But in following code check the first database value only. what is the issue with below code?

print('<table border="1" cellspacing="0" cellpadding="2">');
 for($x=1; $x<=10; $x++)
    {
     echo "<tr>";
    for($y=1; $y<=10; $y++)
       {
      echo "<td>";


        while($row = mysqli_fetch_array($result)){
        if($row['row_id'] == $x && $row['column_id'] == $y)
        print($row['img_title']);
        else echo"no img";
        }


      echo $x . $y;
      echo "</td>"; 
       }
     echo "</tr>";
    }
print('</table>');

Upvotes: 0

Views: 147

Answers (1)

invisal
invisal

Reputation: 11181

while($row = mysqli_fetch_array($result)) {
   // ....
}

Because this code will fetch all the rows once (in your case, your first column and first row) and you cannot reuse it at the other column and row. You can fetch all the rows and store in temporary array.

For example

while($row = mysqli_fetch_array($result)) {
   $temp[$row['row_id']][$row['column_id']] = true;
}

Then in your nested loop:

for($x = 1;  $x <= 10; $x++) {
   for($y = 1; $y <= 10; $y++) {
       if (isset($temp[$x][$y])) {
           print("got");
       }
   }
}

Upvotes: 2

Related Questions