Home » Php » php – How to store multiple files name into phpmyadmin database using foreach?

php – How to store multiple files name into phpmyadmin database using foreach?

Posted by: admin February 25, 2020 Leave a comment

Questions:

The code below does not work. What is the solution for this problem OR any suggestion and what is the most correct way to solve this problem?

HTML Code

<form action="includes/galleryAddImagesCMS.inc.php" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td><div class="container">
                    <div class="upload-btn-wrapper">
                        <label>
                        <input type="hidden" name="albumName" value="<?php echo $albumName ?>"/>
                        <input type="file" id="uploadFile" name="uploadFile[]" multiple/>

                        Choose File
                        </label>
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td><div id="image_preview"></div></td>
        </tr>
        <tr>
            <td>
                <input type="submit" class="btn btn-success" name='submitImage' value="Upload Image"/>
            </td>   
        </tr>
    </table>
</form>

The following below is PHP CODE

<?php 
if(isset($_POST['submitImage'])){
            $albumName = mysqli_real_escape_string($conn,$_POST['albumName']);
            $sqlAlbumname="INSERT INTO gallery (GalleryName, Creationdate) VALUES ('$albumName', CURRENT_TIMESTAMP())";

            if(mysqli_query($conn,$sqlAlbumname)){

                foreach ($_FILES["uploadFile"]["name"] as $key => $imagesname) {

                    $sqlPhotoGallery="INSERT INTO photogallery (PhotoName, Creationdate, GalleryID) 
                    VALUES ('$imagesname', CURRENT_TIMESTAMP(), (SELECT last_insert_id() FROM gallery))";

                    if(mysqli_query($conn,$sqlPhotoGallery)){
                        echo "success";
                    }
                }
            }
        }
How to&Answers:

I think there is an syntax error in your query

\You can use else condition to print the error of query
if(mysqli_query($conn,$sqlPhotoGallery)){
    echo "success";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

in your current code if you have multiple files then it will store multiple records in database.

you can use JSON to store file in single row