Chino. Chino. - 2 years ago 77
PHP Question

Associate image to a row on database php

So, I have a folder with images, each image having a number that corresponds to a "productid" on my database. How can I show the images, each one corresponding to the correct id? I'm working with php at the moment.



$type=$conn->prepare('SELECT ProdutoTipo FROM produtos');
$id=$conn->prepare('SELECT ProdutoID FROM produtos');


function addZero($number){
case 1: return '00'.$number;
case 2: return '0'.$number;
case 3: return $number;
default: return $number;

function getImage($type, $id){

//$imageList = array(scandir('./images/components/'.$type.'/'));
$imageList = array_diff(scandir('Imagens/'.$type) array('..', '.'));
if(in_array(addZero($id).'.jpg', $imageList, true)){
echo addZero($id) . '.jpg';
} elseif(in_array(addZero($id).'.png', $imageList, true)){
echo addZero($id) . '.png';
} elseif(in_array(addZero($id).'.jpeg', $imageList, true)) {
echo addZero($id) . '.jpeg';
} else{
echo '9999.jpg';

Answer Source

if your image folder is stored in YOUR_PATH and image filenames are something like image_{product_id}.jpg you can first get all the product ids from the db then loop through them like this:

    <?php foreach($product_id_list as $product_id){ ?>
       <img src="YOUR_PATH/image_<?php echo $product_id ?>.jpg" />
    <?php } ?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download