在PHP中上传多个文件&插入MySQL的路径 [英] Upload Multiple Files in PHP & INSERT path to MySQL

查看:101
本文介绍了在PHP中上传多个文件&插入MySQL的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个表单,可以从PHP脚本上载多个文件,然后将其插入带有路径的数据库中.这是我的代码

I've setup a form to upload multiple files from a PHP script and then insert it into the Database with path. Here's my code

<form action="" method="post" enctype="multipart/form-data">
<tr class='first'>
    <td>Property Image : </td>
    <td>
        <input type="file" name="pic_upload[]" >
        <input type="file" name="pic_upload[]" >
        <input type="file" name="pic_upload[]" >
    </td>
</tr>
<tr class='first'>
    <td>&nbsp;</td><td><input type="submit" name="create" value="Add"  /></td>
</tr>
</form>
<?php
if(isset($_POST['create'])) {
    $path = "images/";
    for ($i=0; $i<count($_FILES['pic_upload']['name']); $i++) {
        $ext = explode('.', basename( $_FILES['pic_upload']['name'][$i]));
        $path = $path . md5(uniqid()) . "." . $ext[count($ext)-1]; 
        move_uploaded_file($_FILES['pic_upload']['tmp_name'][$i], $path);
    }
    $sql = "INSERT INTO post (`image`) VALUES ('$path');";
    $res = mysqli_query($con,$sql) or die("<p>Query Error".mysqli_error()."</p>");
    echo "<p>Post Created $date</p>";
}
?>  

脚本成功运行,但是在列内的数据库端看起来像这样.

The Script runs successfully, but at the database end inside the column it looks like this.

images/8de3581eb72ee7b39461df48ff16f4a3.jpg024fae942ae8c550a4bd1a9e028d4033.jpg380cc327df25bc490b83c779511c015b.jpg

images/8de3581eb72ee7b39461df48ff16f4a3.jpg024fae942ae8c550a4bd1a9e028d4033.jpg380cc327df25bc490b83c779511c015b.jpg

请帮助我

推荐答案

$path = "images/";移动到for循环内.否则,您将追加到文件名,而不在每次迭代后重设文件名.实际上,您根本不需要为该前缀使用变量.您只需立即写'images/' . md5(uniqid()) . "." . $ext[count($ext)-1].

Move $path = "images/"; inside the for loop. Otherwise you are appending to the filename without resetting it after each iteration. Actually, you don't need to use a variable for that prefix at all. You can simply write 'images/' . md5(uniqid()) . "." . $ext[count($ext)-1] immediately.

要将值写入数据库,您也可以在每次迭代中运行查询,或者将路径添加到根据SQL语法转换为逗号分隔的插入列表的数组.

To write the values to the database, you can either run the query in each iteration as well or add the paths to an array which is transformed to the comma-separated insertion list according to the SQL syntax.

这篇关于在PHP中上传多个文件&amp;插入MySQL的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆