-2

I am making a website which allows the user to add his annonce(or product) for sell, the annonce have simple info + multiple images.

What i want is to make the user select the multiple images one by one, and each time he select an image it shows up in specific div and when he click the 'create' btn it sent and store everything in the sql database. i did make the images shows in the div using js succefully but the problem is that only one image is being uploaded to database...

and if i select the multiple images all in one time, it only shows one image in the specified div, but all the images are sent to the database...

i want the user to select the images one by one, and in each time the selected img shows in the specific ('display_img') div, after all of that the user clicks create and everything is sent .

here is my code:

<form action="annonces/addAnnonce.php"method="post"enctype="multipart/form-data">
                            <div class="mb-3">
                            <label class="form-label">Annonce Title</label>
                            <input type="text" class="form-control"name="title">
                            </div>
                            <div class="mb-3">
                            <label class="form-label">Category</label>
                            <select class="form-select"name="category" aria-label="Default select example">
                                <option value="cars">cars</option>
                            </select>
                            </div>
                            <div class="mb-3">
                            <label class="form-label">sub category</label>
                            <select class="form-select"name="sub_category" aria-label="Default select example">
                                <option value="Toyota">Toyota</option>
                            </select>
                            </div>

                            <div class="mb-3">
                            <label class="form-label">Your location</label>
                            <select class="form-select"name="location" aria-label="Default select example">
                                <option value="NY">NY City</option>
                            </select>
                            </div>
                            <div class="display_img d-flex" style="flex-wrap:wrap;"></div>
                            <div class="mb-3"id="inp_cntnr">
                            image dimension should be at least 350x190
                            <label class="form-label"for="img-inp">
                            <img src="images/add-img.webp" alt="your image" width="100px"height="100"/>
                            </label>
                            <input type="file"name="images[]" multiple=""id="img-inp"/>
                            </div>

                            <button type="submit" class="btn btn-primary mt-2 mb-3">CREATE</button>

</form>

and this is the js code to show the selected img each time:

<script>
        const img_id = document.querySelector('#img-inp');
        const img_inpt_container = document.querySelector('#inp_cntnr');
        var uploaded_img = "";

        img_id.addEventListener('change' , function () {
            const reader = new FileReader();
            reader.addEventListener('load' , () => {
                uploaded_img = reader.result;
                var new_div = document.createElement('div');
                new_div.style.width = '100px';
                new_div.style.height = '100px';
                new_div.classList.add('mx-1');
                new_div.classList.add('mb-1');
                document.querySelector('.display_img').appendChild(new_div);
                new_div.style.background = `url(${uploaded_img})`;
                new_div.style.backgroundRepeat ='no-repeat';
                new_div.style.backgroundSize = '100px 100px';
            });

            reader.readAsDataURL(this.files[0]);
        })

    </script>

and finaly the AddAnnonce.php:

if ($_SERVER['REQUEST_METHOD']  == 'POST') {
            $title= $_POST['title'];
            $category = $_POST['category'];
            $sub_category = $_POST['sub_category'];
            $location = $_POST['location'];

            $images = $_FILES['images'];

            $username = $_SESSION['user_info']->username;

            if (!empty($_POST['title']) && !empty($_POST['category']) && !empty($_POST['location'])) {
                $result = add_new_annonce( "$title", "$category" , "$sub_category"  ,"$location" , "$username" );

                if ($result) {
                    $last_id = mysqli_insert_id($conn);
                    $target_dir = "uploads/";
            
                    $allow_types = array('png' , 'jpg' , 'jpeg');
            
                    $images = array_filter($_FILES['images']['name']);
            
                    foreach ($images as $key => $val) {
                        $imageName = basename($_FILES['images']['name'][$key]);
                        $target_path = $target_dir.$imageName;
                        $imageType = strtolower(pathinfo($target_path , PATHINFO_EXTENSION));
            
                        $target_path = $target_dir.uniqid(rand()).".".$imageType;
            
                        if (in_array($imageType , $allow_types)) {
                            if (move_uploaded_file($_FILES['images']['tmp_name'][$key] , $target_path)) {
                                $query = "INSERT INTO annoncements_images(aid , image_path) VALUES($last_id , '$target_path')";
                                $qresult = mysqli_query($conn , $query);
                                if ($qresult)
                                    header('Location:../index.php?added_success');
                            }
                        }
                    }
                } 
                if (!$result) {
                    header('Location:../index.php?adding_error');
                }

            }
        }
    } else {
        header('Location:../index.php?session_error');
    }

i didn't include the add_new_annonce function bcz it works fine and also to make this question as short as possible. i know that is might be confusing but i don't know what the problem is because i am still new to php and this is my first real project. so anything (advice , suggested video... etc) will be very helpfull for me. thanks in advance.

Djaber
  • 5
  • 2

1 Answers1

0

If you want to avoid multiple file selections you have to remove the multiple attribute.

<input type="file"name="images[]" id="img-inp"/>

While that solves your question, you have to ensure all the files are submitted and probably need an (invisible) helper input field, in which you add the files.

See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/multiple#file_input

Uwe
  • 385
  • 1
  • 5
  • 14
  • But I need the user to upload multiple files, if i removed the multiple attr would that allow the user to upload more than one file? – Djaber Aug 10 '22 at 09:36
  • I assume not, but you could just test it. :) That's why I wrote you need probably a hidden Input field to store all the files. You can't have the attribute multiple and limit the upload to a one-at-a-time upload. That is Browser / OS Behaviour. – Uwe Aug 10 '22 at 11:36
  • I have tested it, it didn't work, how do i make the hidden input field store all the files? – Djaber Aug 11 '22 at 06:39
  • That is another question and for you to find out. It could be a bit tricky or over-engineered - but you could look at https://stackoverflow.com/a/47522812/5841606 and https://stackoverflow.com/a/47172409/5841606 Maybe try some stuff out and if you get stuck open a new question. :) – Uwe Aug 11 '22 at 09:04