Alright, a bit of context: I'm trying to display images(the image is in the table) in four boxes at the bottom of a page. However, I can't figure out how to select all four images from one result set. I've been looking around but it feels like none of the answers that I've found apply to what I'm trying to do...
my SQL is:
SELECT image FROM products WHERE popular = '1'
image is the image name that i'm pulling from the table.(i.e 'image'.jpg)
and this is the PHP I currently have(pardon if it's nasty, it's been changed multiple times in the past hour and a half, as no solution I've tried has worked:)
$sql_getpopular = "SELECT image FROM products WHERE popular='1'";
$result_getpopular = $mysqli->query($sql_getpopular);
$rows_getpopular = mysqli_fetch_row($result_getpopular);
$rows[0] = $rows_getpopular;
$rows_getpopular = mysqli_fetch_row($result_getpopular);
$rows[1] = $rows_getpopular;
$rows_getpopular = mysqli_fetch_row($result_getpopular);
$rows[2] = $rows_getpopular;
$rows_getpopular = mysqli_fetch_row($result_getpopular);
$rows[3] = $rows_getpopular;
also, i've tried doing this in a loop, but that didn't work either. that's why I've got it all written out like this.
and here is what I'm trying to display it in:
<div><?php echo "<img src='images/products/" . $rows[0] . ".jpg'>"; ?></div>
<img id="spacing">
<div><?php echo "<img src='images/products/" . $rows[1] . ".jpg'>"; ?></div>
<img id="spacing">
<div><?php echo "<img src='images/products/" . $rows[2] . ".jpg'>"; ?></div>
<img id="spacing">
<div><?php echo "<img src='images/products/" . $rows[3] . ".jpg'>"; ?></div>
答案 0 :(得分:1)
Your main issue is with
$rows[0] = $rows_getpopular;
as mysqli_fetch_row()
returns a enumerated array so it would need to be
$rows[0] = $rows_getpopular[0];
Using loops - ie. while()
and foreach()
- specifically could reduce your code
to get the image
into $rows
use while()
-
$sql_getpopular = "SELECT image FROM products WHERE popular='1'";
$result_getpopular = $mysqli->query($sql_getpopular);
while($rows_getpopular = mysqli_fetch_row($result_getpopular)){
$rows[] = $rows_getpopular[0];
}
to echo the image
values, use foreach()
-
<?php foreach($rows as $row){ ?>
<div><?php echo "<img src='images/products/" . $row . ".jpg'>"; ?></div>
<img id="spacing">
<?php } ?>