简体   繁体   中英

PHP Multiple file upload and store the names in Database

I am PHP beginner and building my own practice project (I have thought it something like used car sale online site) My problem is very similar to multiple file upload sql/php and Multiple file upload in php

Here are list of my problems I want to upload image in a directory and store it's name in database. So far below code is working fine (if I upload 1 file). I am trying to add 3 more file input option so that user can upload upto 4 images.

So far trying different codes available in stackoverflow and other online sites, I have been able to atleast upload the multiple files in my directory. But the real problem is that I don't know how I would store the name of the file in database .

(In most of the tutorials and suggestions, I found I should use 1 input file type with multiple attributes or name equals array like file[] and run foreach loop. But I couldn't figure out how would go ahead and get the file name of each input and store it in database.

Below are my code for the reference.

    //this is my form.addVehicle.php file to process the form

    <?php
define("UPLOAD_DIR", "../uploads/");
// Check if image file is a actual image or fake image
if(isset($_POST["submit"]))  {
    $name = "default.jpg";
    if (is_uploaded_file($_FILES["myFile"]['tmp_name'])) {
        $myFile = $_FILES["myFile"];
        if ($myFile["error"] !== UPLOAD_ERR_OK) {
            echo "<p>An error occurred.</p>";
            exit;
        }
        // ensure a safe filename
        $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
        // don't overwrite an existing file
        $i = 0;
        $parts = pathinfo($name);
        while (file_exists(UPLOAD_DIR . $name)) {
            $i++;
            $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
        }
        // preserve file from temporary directory
        $success = move_uploaded_file($myFile["tmp_name"],
            UPLOAD_DIR . $name);
        if (!$success) {
            echo "<p>Unable to save file.</p>";
            exit;
        }
        // set proper permissions on the new file
        chmod(UPLOAD_DIR . $name, 0644);
    }
    include_once ('../class/class.Vehicle.php');

    $vehicle = new Vehicle(
        $_POST['make_id'],
        $_POST['yearMade'],
        $_POST['mileage'],
        $_POST['transmission'],
        $_POST['price'],
        $_POST['zone_name'],
        $name,
        $_POST['description']
    );
}
?>      
    //To give a try, tested is_uploaded_file condition four different times with //different file name id like myFile1,myFile2...and path variable as $name1, //$name2...and it works as I want it to be...but I'm sure that' not the correct //way to do it..

    //This is my class file with name class.Vehicle.php 

    include_once('class.pdoDbConnnection.php');

    class Vehicle{
        private  $make_id;
        private  $yearMade;
        private  $mileage;
        private  $transmission;
        private  $price;
        private  $zone_name;
        private  $image_path;
        private  $description;

        public function __construct($make_id, $yearMade, $mileage, $transmission, $price, $zone_name, $image_path, $description){

            $this->make_id = $make_id;
            $this->yearMade = $yearMade;
            $this->mileage = $mileage;
            $this->transmission= $transmission;
            $this->price = $price;
            $this->zone_name = $zone_name;
            $this->image_path = $image_path;
            $this->description = $description;

            try{
                $sql = "INSERT INTO cars (car_id, make_id, yearmade, mileage, transmission, price, zone_name,image_path, description) VALUES (?,?,?,?,?,?,?,?,?)";
                $pdo = new DBConnection();
                $stmt = $pdo->prepare($sql);
                $stmt->execute(array(NULL,$this->make_id,$this->yearMade,$this->mileage,$this->transmission,$this->price,$this->zone_name,$this->image_path,$this->description));

            }
            catch (PDOException $e)
            {
                echo $e->getMessage();
            }
        }
    }

    Here are my mySql table columns (I want to insert file names in the column..while displaying it in the client side, I'm using it this way: <img alt="image" class="img-responsive" src="../uploads/<?php echo $row['image_path'] ?>">
    car_id , make_id , zone_id, yearmade, mileage, transmission, price, image_path, image_path1, image_path2, image_path3, description


    This is my client side form to add new cars....
    ..................
    <form class="form-horizontal" role="form" method="post" action="../includes/form.addVehicle.php" enctype="multipart/form-data">
    .....................
                <div class="form-group">
                    <label for="description" class="col-sm-2 control-label">Upload Image</label>
                    <div class="col-sm-4">
                        <input type="file" class="form-control" id="myFile" name="myFile">
                    </div>
                </div>
                <div class="form-group">
                    <label for="description" class="col-sm-2 control-label">Upload Image</label>
                    <div class="col-sm-4">
                        <input type="file" class="form-control" id="myFile1" name="myFile2">
                    </div>
                </div>
                <div class="form-group">
                    <label for="description" class="col-sm-2 control-label">Upload Image</label>
                    <div class="col-sm-4">
                        <input type="file" class="form-control" id="myFile3" name="myFile3">
                    </div>
                </div>
    ..............

Finally I ended up with the following code.

PS Thanks to @Andy-Brahman insight at Multiple file upload in php

<?php
if(isset($_POST['submit'])){
$uploads_dir = '../test_uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        // I don't want to overwrite the existing file
        $i = 0;
        $parts = pathinfo($name);
        while (file_exists($uploads_dir . "/" . $name)) {
            $i++;
            $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
        }
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
    // Test to see if I get the uploaded file name which i want to insert into database table column.
    echo "<pre>";
    print_r($_FILES['pictures']['name'][0]);
    echo"</br></br>";
    print_r($_FILES['pictures']['name'][1]);
    echo"</br></br>";
    print_r($_FILES['pictures']['name'][2]);
    echo"</br></br>";
    print_r($_FILES['pictures']['name'][3]);
    echo"</br></br>";
    echo "</pre>";
    // test succeeds . Now I guess I can do something like $picture0 = $_FILES['pictures']['name'][0]);
    // and insert $picture0,$picture1...into database..
    // Am I doing everything correctly?


}

I will make example, you just adapt it for yourself.

    <form action="file_reciever.php" enctype="multipart/form-data" method="post">
<input type="file" name="files[]" multiple/>
<input type="submit" name="submission" value="Upload"/>
</form>

the PHP goes ( file_reciever.php ):

<?php
    if (isset($_POST['submission'] && $_POST['submission'] != null) {
        for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
            //Get the temp file path
            $tmpFilePath = $_FILES['files']['tmp_name'][$i];

            //Make sure we have a filepath
            if ($tmpFilePath != "") {
                //Setup our new file path
                $newFilePath = "./uploadFiles/" . $_FILES['files']['name'][$i];

                //Upload the file into the temp dir
                if (move_uploaded_file($tmpFilePath, $newFilePath)) {

                    //Handle other code here

                }
            }
        }
    }
?>

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