如何将许多图像添加到mysql数据库?

时间:2012-12-25 09:40:28

标签: php mysql

我有一个表单,可以将多个选定的文件上传到该文件夹​​。我只需要找到如何使用PHP将它们插入数据库?

HTML表单

<form name="demoFiler" id="demoFiler" enctype="multipart/form-data">
<input type="file" name="multiUpload" id="multiUpload" multiple />
<input type="submit" name="submitHandler" id="submitHandler" value="Upload" class="buttonUpload" />
</form>

PHP代码

if($_SERVER['REQUEST_METHOD'] == "POST"){
    if(move_uploaded_file($_FILES['file']['tmp_name'], "uploads/".$_FILES['file']['name'])){
        echo($_POST['index']);
    }
    exit;
}

这是我的代码,首先我无法将文件移动到上传文件夹:

<?php

$username = "root";
$password = "";
$host = "localhost";
$database = "db_holiday";

// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

// Select your database
mysql_select_db ($database);

if($_SERVER['REQUEST_METHOD']=="POST")
{
    foreach ($_FILES['multiUpload']['name'] as $fileName) { 
        $uploaddir= '/upload/';
    $uploadfile = $uploaddir . basename($fileName);
        if (move_uploaded_file($fileName, $uploadfile)) {
            echo "File is valid, and was successfully uploaded.\n";
        } else {
            echo "Possible file upload attack!\n";
        }
    }
}

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

2 个答案:

答案 0 :(得分:4)

HTML:

<input type="file" name="multiUpload[]" id="multiUpload" multiple />

PHP:

foreach ($_FILES['multiUpload'] as $fileName) { 
    //write your code here
    //$fileName
}

答案 1 :(得分:0)

使用2个input type="file"元素

<input type="file" name="img_1" />
<input type="file" name="img_2" />

使用

访问每个文件
$_FILES['img_1'][];
$_FILES['img_2'][];

或者您也可以使用像

这样的数组
<input type="file" name="img[]" />
<input type="file" name="img[]" />
<!--Which is often used in checkboxes-->

使用

访问每个图像
$_FILES['img']['tmp_name'][0];
$_FILES['img']['tmp_name'][1];