Chino. Chino. - 5 months ago 14
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.

<?php

require('connection.php');

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

?>

<?php
function addZero($number){
switch(strlen((string)$number)){
case 1: return '00'.$number;
break;
case 2: return '0'.$number;
break;
case 3: return $number;
break;
default: return $number;
break;
}
}

function getImage($type, $id){

require('connection.php');
//$imageList = array(scandir('./images/components/'.$type.'/'));
$imageList = array_diff(scandir('Imagens/'.$type) array('..', '.'));
//var_dump($imageList);
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

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:

<html>
<body>
    <?php foreach($product_id_list as $product_id){ ?>
       <img src="YOUR_PATH/image_<?php echo $product_id ?>.jpg" />
    <?php } ?>
</body>
</html>
Comments