John Davidson

PHP indicate main image

0 comments
Message:


I'm trying to create an image uploader where users can select 'main image' or 'primary image'. After they select one, it's name will be stored in a hidden input. When they click on the upload button, the main image should set 'is_mainimage = 1' in the database, and the rest should be 'is_mainimage = 0'. My problem is that I can't set it to 1. I've tried different ways but I only got these results:



  1. All images' is_mainimage set to 1.

  2. All images' is_mainimage set to 0.

  3. Always the first uploaded image's is_mainimage set to 1.


This is how my database looks like:


id | productid | thumbnailimage | is_mainimage
1 | 12 | 1.jpg | 0
2 | 12 | 2.jpg | 1

And this is my code:


for ($i = 0; $i < $counted; $i++) {
$file = $filesTempName[$i];
$is_mainimage = 0;
if (is_uploaded_file($file) && !empty($file)) {
if($_FILES["images"]["name"][$i] == $_POST['mainimage']){
$is_mainimage[$i] = 1;
} else {
$is_mainimage[$i] = 0;
}
$data = "uploads/" . time() . $_FILES["images"]["name"][$i];
move_uploaded_file($file, $data);

$statement->bind_param("sii", $data, $productid, $is_mainimage);
$statement->execute();
}
}

The hidden input is $_POST['mainimage']



My Answer:
It looks like you are trying to set the is_mainimage value based on whether the uploaded image is the main image selected by the user. However, in your code, you are using $is_mainimage[$i] to store the value, which is incorrect.

You should simply use $is_mainimage to store the value of whether the current image is the main image or not. Here is the corrected code snippet:

php
for ($i = 0; $i < $counted; $i++) {
$file = $filesTempName[$i];
$is_mainimage = 0;
if (is_uploaded_file($file) && !empty($file)) {
if($_FILES["images"]["name"][$i] == $_POST['mainimage']){
$is_mainimage = 1;
} else {
$is_mainimage = 0;
}
$data = "uploads/" . time() . $_FILES["images"]["name"][$i];
move_uploaded_file($file, $data);

$statement->bind_param("sii", $data, $productid, $is_mainimage);
$statement->execute();
}
}


By making this change, the is_mainimage value should now be correctly set based on whether the current image is the main image selected by the user.

Rate this post

4 of 5 based on 1290 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us