Reputation: 21
I'm a beginner in php and i'd like to output 3 fields from my database to my website which included a bloc image,text and name. using a foreach i can only get 2 out of the three.
<table border="2px">
<tr>
<th> Brand</th>
<th> Images</th>
<th> Details</th>
</tr>
<?php
$tex = [];
$query = mysqli_query($conn, "SELECT * FROM upload");
while ($row = mysqli_fetch_assoc($query)) {
$images[] = $row['image'];
$br[] = $row['name'];
$det[] = $row['text'];
}
foreach (array_combine($det, $images) as $text => $image) {
echo "<tr><td>";
echo $name;
echo "</td>";
echo "<td>";
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'"/>';
echo "<td>";
echo $text;
echo "</td>";
echo "</td></tr>";
}
?>
</table>
that is a snippet of my code where images and text is outputted on the screen and receive and undefined variable in error in line 39 which would be echo $name;
. what should i put in the foreach statement to get it to output all three?
$images[] = $row['image'];
$br[] = $row['name'];
$det[] = $row['text'];
can someone explain these to me as i have an idea what it is doing but i want to be 100.
Upvotes: 2
Views: 32
Reputation: 16963
There's no point using a separate foreach
loop like that. You should simply change your while
loop like this:
while($row = mysqli_fetch_assoc($query)){
echo"<tr><td>";
echo $row['name'];
echo "</td>";
echo "<td>";
echo '<img src="data:image/jpeg;base64,'. base64_encode($row['image']) .'"/>';
echo"<td>";
echo $row['text'];
echo "</td>";
echo"</td></tr>";
}
Upvotes: 1
Reputation: 4715
This would work:
while ($row = mysqli_fetch_assoc($query)) {
$images[] = $row['image'];
$br[] = $row['name'];
$det[] = $row['text'];
}
foreach ($images as $idx => $image) {
echo "<tr><td>";
echo $br[$idx];
echo "</td>";
echo "<td>";
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'"/>';
echo "<td>";
echo $det[$idx];
echo "</td>";
echo "</td></tr>";
}
You are combining only text
and image
. That way you would not know which name
is the corresponding one. My loop solves this by using the index ($idx
) for that. All arrays have the same size, so this works.
Upvotes: 1