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.
Issues
- I am getting the same image in 2 and third array
- How can ignore the 2 and 3 array when there is no data?