简体   繁体   中英

Upload Multiple images to mysql database

I relatively new to PHP. I need to upload multiple images to the database with one button tap. this is the code. I understand that I have to add a foreach loop to go through each image individually(insert the images individually) but I can't seem to find the right place to insert the for each loop. Any answers would be very much appreciated.

<?php

    error_reporting( ~E_NOTICE ); // avoid notice

    require_once 'dbconfig.php';

    if(isset($_POST['btnsave']))
    {
        $carname = $_POST['car_name'];// car name
        $carmodel = $_POST['car_model'];// car model
        $caramount = $_POST['car_amount'];// car amount

        $imgFile = $_FILES['car_image']['name'];
        $tmp_dir = $_FILES['car_image']['tmp_name'];
        $imgSize = $_FILES['car_image']['size'];


        if(empty($carname)){
            $errMSG = "Please Enter Name of the Car.";
        }
        else if(empty($carmodel)){
            $errMSG = "Please Enter Model Number of the car.";
        }
        else if(empty($caramount)){
            $errMSG = "Please Enter the cost of the car.";
        }
        else if(empty($imgFile)){
            $errMSG = "Please Select Image File.";
        }
        else
        {

            $upload_dir = 'user_images/'; // upload directory

            $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

            // valid image extensions
            $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

            // rename uploading image
            $carpic = rand(1000,1000000).".".$imgExt;

            // allow valid image file formats
            if(in_array($imgExt, $valid_extensions)){            
                // Check file size '5MB'
                if($imgSize < 5000000)                {
                    move_uploaded_file($tmp_dir,$upload_dir.$carpic);
                }
                else{
                    $errMSG = "Sorry, your file is too large.";
                }
            }
            else{
                $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";        
            }
        }


        // if no error occured, continue ....
        if(!isset($errMSG))
        {
            $stmt = $DB_con->prepare('INSERT INTO tbl_cars(carName,carModel,carAmount,carPic) VALUES(:cname, :cmodel, :camount, :cpic)');
            $stmt->bindParam(':cname',$carname);
            $stmt->bindParam(':cmodel',$carmodel);
            $stmt->bindParam(':camount',$caramount);
            $stmt->bindParam(':cpic',$carpic);
            if($stmt->execute())
            {
                $successMSG = "new record succesfully inserted ...";
                header("refresh:5;car_display.php"); // redirects image view page after 5 seconds.
            }
            else
            {
                $errMSG = "error while inserting....";
            }
        }
    }
?>

I know I need to add a simple for each loop, execution is failing me. Somebody Save Me

This is the HTML bit that uploads

 <tr>
        <td><label class="control-label">Car Img.</label></td>
        <td><input class="input-group" type="file" name="car_image" multiple="multiple" accept="image/*" /></td>

You need to specify in html that is it will be an array of files and then call the foreach in your php, basically the post will be an array.

My example is not using PDO or adapted to your example but it is working in uploading multiple files.

PHP:

<?php
if(isset($_FILES['files'])){
    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];  
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }       
        $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
        $desired_dir="user_data";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"user_data/".$file_name);
            }else{                                  //rename the file if another one exist
                $new_dir="user_data/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
            mysql_query($query);            
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}
?>

HTML

<form action="yourphpfile.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple="" />
    <input type="submit"/>
</form>

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