Question

I have a database with 3 columns: product_id, product_name, product_image. I need to run a query to retrieve all values and then create a list of that data.

product_id | product_name | product_image |
1          | ball         | ball.jpg      |
2          | shirt        | shirt.jpg     |
3          | car          | car.jpg       |

This is the code I'm using:

$q1 = $db->Execute("select * from products");

$q1_items = array();

while(!$q1->EOF){
    $q1_items[] = $q1->fields;
    $q1->MoveNext();
}
foreach ($q1_items as $items) {
    echo '<a href="index.php?main_page=product_info&products_id='. $items['products_id'] .'"><img src="images/'. $items['products_image'].'" alt="'. $items['products_name'].'" title="'. $items['products_name'].'" /></a>\n';
}

This is a Zen Cart site so $db->Execute is already defined and works just fine.

The output I'm expecting is like this:

<a href="index.php?main_page=product_info&products_id=1"><img src="ball.jpg" alt="ball" title="ball" /></a>
<a href="index.php?main_page=product_info&products_id=2"><img src="shirt.jpg" alt="shirt" title="shirt" /></a>
<a href="index.php?main_page=product_info&products_id=3"><img src="car.jpg" alt="car" title="car" /></a>

However, I'm getting this:

<a href="index.php?main_page=product_info&products_id=1"><img src="ball.jpg" alt="ball" title="ball" /></a>
<a href="index.php?main_page=product_info&products_id=1"><img src="shirt.jpg" alt="ball" title="ball" /></a>
<a href="index.php?main_page=product_info&products_id=1"><img src="car.jpg" alt="ball" title="ball" /></a>
<a href="index.php?main_page=product_info&products_id=2"><img src="ball.jpg" alt="shirt" title="shirt" /></a>
<a href="index.php?main_page=product_info&products_id=2"><img src="shirt.jpg" alt="shirt" title="shirt" /></a>
<a href="index.php?main_page=product_info&products_id=2"><img src="car.jpg" alt="shirt" title="shirt" /></a>
<a href="index.php?main_page=product_info&products_id=3"><img src="ball.jpg" alt="car" title="car" /></a>
<a href="index.php?main_page=product_info&products_id=3"><img src="shirt.jpg" alt="car" title="car" /></a>
<a href="index.php?main_page=product_info&products_id=3"><img src="car.jpg" alt="car" title="car" /></a>

Basically, duplicates the entire row for each image and changes only image name. What am I doing wrong and how do I get the output I need?

Was it helpful?

Solution

Shouldn't you be using the value

foreach ($q1_items as $item => $items) {
    echo '<a href="index.php?main_page=product_info&products_id='. $items['products_id'] .'"><img src="images/'. $items['products_image'].'" alt="'. $items['products_name'].'" title="'. $items['products_name'].'" /></a>\n';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top