简体   繁体   中英

Upload Multiple Images with PHP and put it into MYSQL Database

Edit : solved! credits to @kaylined and @uli . i edited the code just in case someone in the future face the same problem with uploading multiple images at once and stored it into MYSQL Database.

i am trying to create upload multiple images at once script with PHP and MYSQL. but the script isn't working well. i don't know where i do wrong. maybe you guys could help. here is my code :

PS : images are uploaded successfully, the file name is also stored to database successfully. but the "slug" variable is stored to database as "Array"

Input Form

<form method="POST" action="action-add-images.php" enctype="multipart/form-data">
    <input type="hidden" name="slug" value="<?php echo $_GET['slug']; ?>">
    <label>Upload Files</label>
    <input required type="file" name="image[]" class="form-control-file" multiple>
    <button type="submit" class="btn btn-block btn-primary my-3 ">Upload Images</button>
</form>

Action File

<?php
include "../connect.php";
    foreach ($_FILES['image']['name'] as $key => $name){
        $newFilename = date('YmdHis',time()).mt_rand().'.jpg';
        move_uploaded_file($_FILES['image']['tmp_name'][$key], '../img/' . $newFilename);
        $image = '../img/' . $newFilename;
        $slug = $_POST['slug'];
        mysqli_query($conn,"INSERT INTO product_image (slug,image) values ('$slug','$newFilename')");
    }
    header('location:product.php');
?>

Slug is saving as an array, because it is an array.

$slug = $_POST['slug'];

should solve your problem, assuming the slug elements are added in the same order as your files.

As per the comments, the above PHP has been fixed and the fixed HTML below - all I did was remove the array directive from the input:

<form method="POST" action="action-add-images.php" enctype="multipart/form-data">
<input type="hidden" name="slug" value="<?php echo $_GET['slug']; ?>">
<label>Upload Files</label>
<input required type="file" name="image[]" class="form-control-file" multiple>
<button type="submit" class="btn btn-block btn-primary my-3 ">Upload Images</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM