简体   繁体   中英

Storing path in mysql database for multiple drag and drop upload

I have been following this tutorial and it works great but I want to store the path of each image in a mysql database. My code is

$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');


if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
 }


if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){

$pic = $_FILES['pic'];

if(!in_array(get_extension($pic['name']),$allowed_ext)){

            exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}   

if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){


    exit_status('File was uploaded successfuly!');
}

 }

 exit_status('Something went wrong with your upload!');


// Helper functions

function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}

function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}

What would be the best way to loop through the files and insert the path to a mysql database?

Because of the nature of your question, I'll start with creating the table to store the names of the uploaded images.

CREATE TABLE IF NOT EXISTS `images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;  

The above table has just these few fields, but if you think you need some more you can add additional fields to the table at any point later.
Now for the PHP part.

$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');

// create the PHP Data Object to communicate with your MySQL database
$host = 'localhost';
$dbname = 'db_name';  // the database name in which you've created the above table  
$user = 'username';  // replace with your username
$pass = 'password';  // same goes for password
$db = new PDO("mysql:host=$host;db=$dbname", $user, $pass);  

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    exit_status('Error! Wrong HTTP method!');
}

if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){

    $pic = $_FILES['pic'];

    if(!in_array(get_extension($pic['name']),$allowed_ext)){
        exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
    }   

    if($demo_mode){

        // File uploads are ignored. We only log them.

        $line = implode('       ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
        file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);

        exit_status('Uploads are ignored in demo mode.');
    }

    // Move the uploaded file from the temporary
    // directory to the uploads folder:

    if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
        // now insert the data in the database
        $stm = "INSERT INTO images (name,date) VALUES (:name,:date)";
        $query = $db->prepare($stm);
        $query->execute(array(':name'=>$pic['name'], 
                              ':date'=>date("Y-m-d H:i:s", time())
                              )
                        );
        exit_status('File was uploaded successfuly!');
    }

}

exit_status('Something went wrong with your upload!');

// Helper functions
// .....

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