I am trying to retrieve multiple / single images from DB using jquery. as per the way I tried, I am receiving only the first image. The rest are not visible.
For saving multiple images I am using comma after to separate. EX: saved 2 imaged named x.jpg and y.jpg, The image name will be saved in the column as x.jpg,y.jpg and image will be uploaded to the folder.
var image_DB = data[0].pimage; //FROM DB COLUMN
var upload_dir = "../uploads/"; //IMAGE PATH
var img = document.createElement("IMG");
img.height = 90;
img.weight = 90;
if(image_DB !== ''){ //IF IMAGE COLUMN HAS A VALUE || IMAGE
if(image_DB.includes(',') !== false){ //IF THE COLUMN CONTAINTS MULTIPLE IMAGES
console.log('Multiple Images Here');
var image = image_DB.split(',');//SPLITTING IT WITH COMMA -1
$.each(image, function(key, value){ //ITERATING VALUES TO FIND FILE NAME
img.src = upload_dir+value; //UPDATING IMAGE SOURCE
});
}else{//IF THE COLUMN CONTAINTS ONE IMAGE WITHOUT COMMA
console.log('Single Image Here');
img.src = upload_dir+image_DB;
}
}else{ //IF NO IMAGE EXISTS
console.log('Nothing is in DB');
}
$('#preview').prepend(img);
Where am I making the mistake? Please suggest.
The way its done in PHP is
if($row['pimage'] !== ''){
if(strpos($upload_dir.$row['pimage'],',')!== false){
$image = explode(',',$row['pimage']);
$imageArr = '';
foreach ($image as $im){
$imageArr .= '<img src="'.$upload_dir.$im .'"width="150" height="150"/>';
}
}
else{
$imageArr = '<img src="'.$upload_dir.$row['pimage'].'"width="150" height="150"/>';
}
}else{
$noImage = 'No Image.jpg';
$imageArr = '<img src="'.$upload_dir.$noImage.'"width="150" height="150"/>';
}
imgtag for each of them. What happens now is that you create one image, and change it'ssrcattribute multiple times, this will naturally only lead to one image being displayed.imgtag represents one single image. You can of course change thesrcattribute dynamically which will cause the image to change as well. But you can not have multiple images showing at the same time with only oneimgtag.foreachcreates a new element for each instance. The.=keeps adding to the html string every iteration