Deleting a product with related pictures with PHP - php

In my PHP application I have products which have images in 3 sizes - big, thumbnails and small thumbnails. Each image is stored in a separate folder:
Images - /gallery
Thumbnails - /gallery/bigthumbs
Small thumbnails - /gallery/thumbs
Each product has its unique ID. The file names of all images of a certain product are the same. The path to the images for the product are being stored in the database with the same ID as the associated product ID.
Each product can have more than 1 image but in the database, where I store the paths and the names of the images for each product, all the images are stored with the same ID, the same as the product ID.
So, if a product with ID 56 has 2 images in the database, those images will be stored like this:
ID->56, image1name, bigthumb1name, thumb1name
ID->56, image2name, bigthumb2name, thumb2name
What I'm trying to do is - delete all the images associated with the product which is being deleted. The code I've written is as follows:
$imagename_query = mysql_query("SELECT image FROM gallery WHERE id='$productid'", $connect);
$imagename_result = mysql_fetch_array($imagename_query);
foreach($imagename_result as $imagename) {
$bigimage = "../gallery/$imagename";
unlink($bigimage);
$picture = "../gallery/bigthumbs/$imagename";
unlink($picture);
$thumb = "../gallery/thumbs/$imagename";
unlink($thumb);
}
$gallery_query = mysql_query("DELETE FROM gallery WHERE id='$productid'", $connect);
$query = mysql_query("DELETE FROM products WHERE ID='$productid'", $connect);
The problem is that the code above deletes only 1 image - no difference how many images there are with the same ID.
Could anybody help me figure this out?
Thanks in advance.

this line is the problem
$imagename_result = mysql_fetch_array($imagename_query);
should be
while ($row = mysql_fetch_array($imagename_query))
{
$bigimage = "../gallery/{$row['image']}";
unlink($bigimage);
// etc
}
I not sure is it truth for your case -- do you have multiple products with same name?
your approach could be a bit risky ...
you can make the folder path unique by embed the product id
such as
/gallery/{$product_id}/{$product_name}.*

since you have more images you shoud use:
while ($current_imagename_result = mysql_fetch_array($imagename_query))
instead of
$imagename_result = mysql_fetch_array($imagename_query);
and after you will have to use $current_imagename_result instead of yor varable

Thanks everybody for help. I've managed to solve this in the following way:
$imagename_query = mysql_query("SELECT image FROM gallery WHERE id='$productid'", $connect);
$rows_count = mysql_num_rows($imagename_query);
for($i=0; $i<$rows_count; $i++){
$id = mysql_result($imagename_query, $i, 'image');
$bigimage = "../gallery/$id";
unlink($bigimage);
$picture = "../gallery/bigthumbs/$id";
unlink($picture);
$thumb = "../gallery/thumbs/$id";
unlink($thumb);
}
Hope this will help somebody else.

Related

How to fetch images that stored in comma separated format in single row in MySQL?

I am uploading multiple images in the database in a single column with comma separated format. I am first creating a folder for each user and inside that folder, images are stored. car_images is my root directory inside that with the name of logged_in user new directory will create.
My images are stored in below format :
Here, emp_code is unique I am using this as SESSION and for the name of the folder of each user.
as you see car_images column where I am storing image name with ,.
I am using below code to stored images in folders and database. I don't know idea how to fetch all images of a single user.
$car_images_all="";
for($i=0; $i<count($_FILES['car_images']['name']); $i++)
{
$tmpFilePath = $_FILES['car_images']['tmp_name'][$i];
if ($tmpFilePath != "")
{
if (!file_exists('car_images/'.$emp_code))
{
mkdir('car_images/'.$emp_code, 0777, true);
}
$location = 'car_images/'.$emp_code.'/';
$name = $_FILES['car_images']['name'][$i];
$size = $_FILES['car_images']['size'][$i];
list($txt, $ext) = explode(".", $name);
$file= time().substr(str_replace(" ", "_", $txt), 0);
$info = pathinfo($file);
$filename = $file.".".$ext;
if(move_uploaded_file($_FILES['car_images']['tmp_name'][$i], $location.$filename))
{
$car_images_all.=$filename.",";
}
}
}
First of all,
Select all images from database by emp_code (as you want all images of a particular user/emp).
select car_images from TableName where emp_code = $emp_code;
Now, by this you will get one or more rows.
So, add one by one images to array with using explode() function per row (i.e. if row has multiple image name with comma separated).
Use the array as per your choice of manipulation.
Below code will fetch the data from table and save images in array. For more details check the explode function.
$query = "select car_images from table_name where emp_code = 'emp_code'";
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_assoc($result);
$images = $row['car_images'];
$images = explode(',',$images);
foreach($images AS $image){
echo '<img src="car_images/'.$emp_code.'/'.$image.'">';
}
You can use GROUP_CONCAT() function
SELECT GROUP_CONCAT(car_images) FROM TableName
You can use group by also with emp_code or brand_id or any other column whatever your business logic is met.
SELECT GROUP_CONCAT(car_images) FROM TableName GROUP BY emp_code
OR
SELECT GROUP_CONCAT(car_images) FROM TableName GROUP BY brand_id
<?php
$x=0;
$car_img =explode(",",$car_images);
foreach($car_img as $car_images{
$x+=1;0
?>
<?php echo '<img src="'."images/".$car_images.'" width="70" height="70" />';?>

Duplicate a row in sql table

With the code below, im trying to duplicate a product row with ajax in a webshops table, named termek.
If the last product is ID 90, and i copy this, the new product will be ID 91.
Sometimes, and i dont know why, the ID 90(what i copyed), loose the image, the thumb and big cell in the table, or it is renamed or i dont know what going on.
Is this code okay for copying, or whats wrong whit it?
<?php
include_once("../../files/connect.php");
if(!empty($_POST))
{
$id = mysqli_real_escape_string($kapcs, $_POST['id']);
$sql =
"
INSERT INTO termek
(
termek_nev,
termek_seo,
termek_rovid,
termek_hosszu,
termek_thumb,
termek_big,
termek_seo_title,
termek_seo_rovid,
termek_seo_kw,
termek_status,
termek_view,
termek_akcio,
termek_normal_ar,
termek_akcios_ar,
termek_cikkszam,
termek_egyseg,
termek_fooldal,
termek_kiemelt,
termek_suly,
termek_keszlet_db,
termek_keszlet_warning,
termek_min_order,
termek_allapot,
termek_gyarto,
termek_jobb_arat_btn,
termek_tipus,
termek_szavak
)
SELECT
termek_nev,
termek_seo,
termek_rovid,
termek_hosszu,
termek_thumb,
termek_big,
termek_seo_title,
termek_seo_rovid,
termek_seo_kw,
termek_status,
termek_view,
termek_akcio,
termek_normal_ar,
termek_akcios_ar,
termek_cikkszam,
termek_egyseg,
termek_fooldal,
termek_kiemelt,
termek_suly,
termek_keszlet_db,
termek_keszlet_warning,
termek_min_order,
termek_allapot,
termek_gyarto,
termek_jobb_arat_btn,
termek_tipus,
termek_szavak
FROM termek WHERE termek_id = '$id'
";
if(mysqli_query($kapcs, $sql))
{
echo (int)1;
}
else
{
echo mysqli_error($kapcs);
}
}
?>
To solve the problem, i uploaded a noimage.jpg to the products folder. When im editing the copied or the old product and changing its image, i dont delete the old image, if the thumb or big column == noimage.jpg.
Sorry for bad english.

insert array with dynamic amount of values to database

I am attempting to insert an array of image information into my database. The array consists of a ton of image information and originally i started with just allowing 3 images out of the array to be entered into the database.
The images detail goes into a table called print and each of the three image urls has a column of their own to go into, along with a caption for each image, the date the image was taken and its location. All of this info goes into one row with the users id.
// Assign images and data to appropriate variables
$image_one = $feed['0']['images']['standard_resolution']['url'];
$image_one_caption = htmlspecialchars($feed['0']['caption']['text'], ENT_QUOTES);
$image_one_date = $feed['0']['created_time'];
$image_one_location = $feed['0']['location']['name'];
$image_two = $feed['1']['images']['standard_resolution']['url'];
$image_two_caption = htmlspecialchars($feed['1']['caption']['text'], ENT_QUOTES);
$image_two_date = $feed['1']['created_time'];
$image_two_location = $feed['1']['location']['name'];
$image_three = $feed['2']['images']['standard_resolution']['url'];
$image_three_caption = htmlspecialchars($feed['2']['caption']['text'], ENT_QUOTES);
$image_three_date = $feed['2']['created_time'];
$image_three_location = $feed['2']['location']['name'];
However I now want to make it so that the number of prints entered into the table can vary from 3 up to 10 as a maximum. I'm wondering about the best way to do this.
I could simply assign the array values to more variables in the way shown above, however this is bulky and I feel unnecessarily repetitive.
I was thinking about a foreach loop, however I'm uncertain of how to insert each image and each images accompanying data into the correct columns of the users print row.
The other option would be to create a separate print_info table and store the users id and print_job number, then in the print table purely have the image info in separate rows with a print_job column to link the print_job to the users print_info row. is this the best way forward with this little problem?
What about this:
$numOfImages = 4; //the number you want
for ($i=0; $i < $numOfImages; $i++) {
$image = $feed[$i]['images']['standard_resolution']['url'];
$image_caption = htmlspecialchars($feed[$i]['caption']['text'], ENT_QUOTES);
$image_date = $feed[$i]['created_time'];
$image_location = $feed[$i]['location']['name'];
//...operation with $image
}

Random pictures in two pages

I have a table that stores images of three categories: cars, bikes, buses. These images appear on two pages. On the first page, you should see an image of each category, defined so random. On the second page, you should see the remaining pictures. How can I do this using php?
I would prefer to do this in MySQL, you can set the order to:
ORDER BY MD5(ImageNo+UserRandomNumber)
SQL FIddle
You can generate a single random number per user, store this in the session then apply this to the ordering and as long as the number supplied stays the same, the order will remain the same too.
You can indeed use a session to store which images were shown on the first page, and then leave them out on the second page. Without knowing your exact table structure, something like this should work:
<?php
// page 1
session_start();
function get_random_image_id($category)
{
// SELECT id FROM images WHERE category = $category ORDER BY RAND() LIMIT 1
}
function show_image($id)
{
// SELECT * FROM images WHERE id = $id
// echo <img ...>
}
$_SESSION['image_ids'] = array(
get_random_image_id("cars"),
get_random_image_id("bikes"),
get_random_image_id("buses"),
);
foreach($_SESSION['image_ids'] as $image_id)
{
show_image($id);
}
?>
<?php
// page 2
session_start();
function show_images($exclude_ids)
{
$ids = implode(",", $exclude_ids);
// SELECT * FROM images WHERE id NOT IN ($ids)
}
$exclude = array();
if(isset($_SESSION['image_ids'])) // has the user visited page 1?
{
$exclude = $_SESSION['image_ids'];
}
show_images($exclude);
?>

PHP/HTML/mySQL URL Caching Problem

I have this function: http://pastebin.ca/2058418
It basically checks to see if a tables contains some URLs to pictures of a band. If it does, then it will order the table by random, choose the first result and then output the html code to insert the picture. If the table does not have the pictures of that specific band, then it downloads an XML file which contains the image URL's, parses the XML and inserts in into the table, and then gets the HTML code for the image like before.
In terms out html output, you can't tell if the image URL has been cached or not. HOWEVER, when the image URL is cached (for the first time), whatever web browser you use will not display the image. The HTML is fine - the image is linked correctly.
Do you have any ideas? A live version of the site which contains this function is here: http://redfern.me/similar/. I have just emptied the tables, so there shouldn't be many cached URL's. Try choosing a band, and then see if the image loads. You can tell if the URL's where cached or not by looking at the bottom of the page.
basically looks like you wasn't returning after you fetched the image first time.
<?php function getimage($artist){
$api_key = "XXXXXXXXX";
$iquery = mysql_query("SELECT url FROM `images` WHERE artist = '".$artist."' ORDER BY RAND() LIMIT 1");
if($artist != ""){
$artist = str_replace(" ", "+", $artist);
if(mysql_num_rows($iquery) == 0){
$url = "http://developer.echonest.com/api/v4/artist/images?format=xml&api_key=".$api_key."&name=".$artist."&results=20";
$data = file_get_contents($url);
if($data=false){return 'Error Getting Image';}
$images = new SimpleXMLElement($data);
foreach($images as $image){
foreach($image->image as $indimage){
$insiquery = "INSERT INTO images (id, artist, url) VALUES (NULL, '$artist','".$indimage->url."')";
mysql_query($insiquery);
}
}
return "<img src=\"".$indimage->url."\" alt=\"$artist image\" />";
}else{
$imgurl = mysql_fetch_array($iquery);
return"<img src=\"".$imgurl['url']."\" alt=\"$artist image\" />";
}
}
else{
return"Image Aquire Function Error: <i>No Band Specified</i>";
}
return null;
}?>
echo getimage('Britney Spears');
That's simply because when you enter to the "xml call" your var "$imgurl[0]"
is empty :
try something like this :
$images = new SimpleXMLElement($data);
$xmlImgUrl = array();
foreach($images as $image){
foreach($image->image as $indimage){
$xmlImgUrl[] = $indimage->url;
$insiquery = "INSERT INTO images (id, artist, url) VALUES (NULL, '$artist','".$indimage->url."')";
mysql_query($insiquery);
}
}
}
$imgurl = $nrows == 0 ? $xmlImgUrl : mysql_fetch_row($iquery);
if(!empty($imgurl)) echo "<img src=\"".$imgurl[0]."\" alt=\"$artist image\">";
which instantiate an array of image urls when no results in mysql.

Categories