MySQL Question

How to get table data with foreach if my array indexs' are the same

$query = mysqli_query($con,"SELECT id,title,post FROM titlepost");

$data = [];

while($row = mysqli_fetch_assoc($query))
{
$data = $row;
var_dump($data);
}


With this code I get

array(3) { ["id"] => string(1) "1" ["title"] => string(4) "News" ["post"] => string(21) "Here can be your news"
}

array(3) { ["id"] => string(1) "4" ["title"] => string(5) "Maths" ["post"] => string(30) "Here can be your maths' theory"
}

array(3) { ["id"] => string(1) "5" ["title"] => string(6) "Toyota" ["post"] => string(26) "Here can be your car's add"
}


Here I want to get the data with foreach

<?php
foreach($data as $value) { ?>
<tr>
<th><?=$value['id']?></th>
<th><?=$value['title']?></th>
<th><?=$value['post']?></th>
</tr>
<?php }?>

Answer

There is no need to use two separate loops. You can just output the values within the first loop:

$query = mysqli_query($con,"SELECT id,title,post FROM titlepost");

while($row = mysqli_fetch_assoc($query)) {
    ?><tr>
        <th><?=$row['id']?></th>
        <th><?=$row['title']?></th>
        <th><?=$row['post']?></th>
    </tr><?php
}

However, if you want for some reason to store the result in an array (for example to use it multiple times or pass it to a view in an MVC setup), your first loop should look like this:

$query = mysqli_query($con,"SELECT id,title,post FROM titlepost");

$data = [];

while($row = mysqli_fetch_assoc($query))    
{
  $data[] = $row; // this line appends a new item to the $data array, instead of overwriting it, like in your original code
}
Comments