如何在插入mysql之前在数组中存储多个图像

时间:2013-01-29 21:51:18

标签: php mysql

我有一个上传功能,它可以处理一个或多个能够上传到文件夹的文件,然后将索引插入mysql。如何将多个图像存储为数组?

//This upload code to allow users to upload specific files 
<?php
$user_id = $_SESSION['lt_user_id'];
$user_code = $_SERVER['AUTH_USER'];
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';
    }

$host="server.mysql.com"; 
$username="user";
$password="password";
$db_name="db01";
$tbl_name="upload_data";

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");


// Insert data into mysql
$sql="INSERT into $tbl_name (ID, USER_CODE, FILE_NAME, FILE_SIZE, FILE_TYPE) VALUES('$user_id','$user_code','$file_name','$file_size','$file_type'); ";


 $desired_dir="../backup1Jan2013/images/";
        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,"$desired_dir/".$file_name);
            }else{                                  // rename the file if another one exist
                $new_dir="$desired_dir/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
 mysql_query($sql);         
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}



// close connection
mysql_close();


?>


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

1 个答案:

答案 0 :(得分:0)

您可能不希望在数据库的同一字段中存储多个图像。

相反,我会将图像存储在文件系统的文件夹中,并将文件夹的位置存储在mysql表中。