0

I have below code on my page and I am displaying dynamically field.

<input type="file" name="pic[1]"   class="work_pic">
<input type="text" name="title[1]" class="form-control">
<input type="text" name="desc[1]"  class="form-control">


<input type="file" name="pic[2]"   class="work_pic">
<input type="text" name="title[2]" class="form-control">
<input type="text" name="desc[2]"  class="form-control">


<input type="file" name="pic[3]"   class="work_pic">
<input type="text" name="title[3]" class="form-control">
<input type="text" name="desc[3]"  class="form-control">

Below is my logic code

$title=$_POST['title'];
$desc=$_POST['desc'];
foreach($title as $key =>$value){ 
    $ogimage=$_FILES['pic']['name'][$key];
    //print_r($ogimage);
    $work_pic =" ";
    $work_dir = "assets/images/uploads/pic/";
    $filename1  = basename($ogimage);
    $extension1 = pathinfo($filename1, PATHINFO_EXTENSION);
    $newrand        = mt_rand();// random number
    $work_pic       = $newrand.'.'.$extension1;
    $target_file = $work_dir . $work_pic;
    $uploadOk = 1;

    if ($uploadOk == 0) {
        $errorMsg[]="Sorry, your file was not uploaded dynamic.";
        $code="5";
    } else {
        if (move_uploaded_file($_FILES["pic"]["tmp_name"][$key], $target_file)) {
            $workimagename= $work_pic;
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

    $insert_array = array(
              'title' => $title[$key],
              'desc' => $desc[$key],
              'pic' => $workimagename,
              'user_id' => $lastUserid,
          );
      
    $sqlwork="INSERT INTO `tbl_abcwork`
                    (`title`, `desc`, `pic`, `user_id`) 
            VALUES (:title,:desc,:pic,:user_id)";
    $stmt= $pdo->prepare($sqlwork);
    $stmt->execute($insert_array);  

My logic is working perfectly if I filled all three with data. I am getting the output

Array ( 
    [title] => testing 
    [desc] => testing 
    [pic] => 1756775265.png 
    [user_id] => 6
   ) 
  Array (
   [title] => testing 
   [desc] => testing 
   [pic] => 869702765.png
    [user_id] => 6 
  )
  Array (
     [title] => testing 
     [desc] => testing 
     [pic] => 1145700947.png 
     [user_id] => 6 
   ) 

If I filled data only in the first fieldset then I am getting output.

Array ( 
  [work_title] => alndlasd 
  [work_year] => lknalksndlaksd 
  [work_pic] => 1332366488.png 
  [user_id] => 7 
) Sorry, there was an error uploading your file.

Array ( 
  [work_title] => 
  [work_year] => 
  [work_pic] => 1332366488.png 
  [user_id] => 7 
) Sorry, there was an error uploading your file.
Array ( 
  [work_title] => 
  [work_year] => 
  [work_pic] => 1332366488.png 
  [user_id] => 7
   ) 

I am getting the data in my database.

enter image description here

Issues

  1. I am getting the same image in 2 and third array
  2. How can ignore the 2 and 3 array when there is no data?
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
user9437856
  • 2,360
  • 2
  • 33
  • 92
  • 1
    Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Jun 25 '20 at 12:31
  • have you tried to clean up (remove empty elements) your 'source' array using `$title=array_filter($_POST['title']);` – jibsteroos Jun 25 '20 at 12:40
  • @RiggsFolly, Apologize for my bad code, I'll not repeat this in future. – user9437856 Jun 25 '20 at 12:43
  • @jibsteroos, I haven't tried array_filter as of now. Let me check this. – user9437856 Jun 25 '20 at 12:44
  • I'm surprised that the query inserts anything at all. You work with named parameters (`:title,:desk,:pic,:user_id`) but your array keys miss the colon. – Michel Jun 25 '20 at 12:52
  • @Michel its sorta-allow to not include the colon on keys, its implied. It makes code more confusing to look at yes, and shouldnt be relied on, but it still works behind the scenes (for now). – IncredibleHat Jun 25 '20 at 12:54
  • @IncredibleHat Mmm, never knew that. And manual doesn't mention it. Makes life a lot easier. – Michel Jun 25 '20 at 12:57
  • 1
    @Michel Just saw this... so yeah, prolly not a good idea to do it :) https://stackoverflow.com/a/9778890/2960971 – IncredibleHat Jun 25 '20 at 12:58
  • @IncredibleHat, So Do I need to add colon in bind param? – user9437856 Jun 25 '20 at 13:30
  • @user9437856 The `$insert_array` keynames would be better off having the colon in them, just to be safe and clear. – IncredibleHat Jun 25 '20 at 13:33

2 Answers2

0

Do you tried by using if?

if (!empty($title) and !empty($desc)) {
//foreach
  if (!empty($_FILES['pic']['name'][$key])) {
  //save
}
//endforeach
}
TacticJuls
  • 304
  • 1
  • 8
0

You're getting all 3 images with the same name in your database because $insert_array['pic'] is being set to $workimagename, which is only being set on successful saving. When your first image saves, $workimagename is being set, and inserted, and then in subsequent loops you're not resetting its value anywhere.

Scoping in a for loop doesn't work quite how you'd expect. For example, if after the for loop you tried to use any variable declared inside the loop (i.e. $uploadOk) you would still be able to get the value from the last iteration of the loop. My first recommendation is at the beginning of the loop do $workimagename = ''; at the very least to reset that value.

But your second issue should be easily fixed with a conditional to verify all data exists before trying to upload the image:

if ($uploadOk == 0) { //will this ever be true?
    $errorMsg[]="Sorry, your file was not uploaded dynamic.";
    $code="5";
} else {
    if ($value) { //this should check if any value exists for this input
        if (move_uploaded_file($_FILES["pic"]["tmp_name"][$key], $target_file)) {
            $workimagename= $work_pic;
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    } else {
        echo "Image was not provided";
    }
}

Maybe instead of checking if ($value) you should check if ($_FILES["pic"]["tmp_name"][$key]) instead. I don't fully remember how PHP handles file uploads like this, but if you check for the existence of the input data before trying to do anything with it, it will allow you to skip over non-existent inputs.

WOUNDEDStevenJones
  • 5,150
  • 6
  • 41
  • 53