2014-11-03 44 views
0

我有这个问题,当我上传图片在数据库中。当我插入查询,我只有一个点击3行。这是HTML文件:在同一张表中上传multy文件时出错

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

,这是我的PHP代码:

<? 
include "../include/config.php"; 

?> 

<? 
if(isset($_FILES['file_array'])){ 
    $id = $_REQUEST['id']; 
    $name_array = $_FILES['file_array']['name']; 
    $tmp_name_array = $_FILES['file_array']['tmp_name']; 
    $type_array = $_FILES['file_array']['type']; 
    $size_array = $_FILES['file_array']['size']; 
    $error_array = $_FILES['file_array']['error']; 
    $image1 = $name_array[0]; 

     for($i = 0; $i < count($tmp_name_array); $i++){ 
     if(move_uploaded_file($tmp_name_array[$i], 
      "test_uploads/".$name_array[$i])){ 
      echo $name_array[$i]." upload is complete<br>"; 

      $add = mysql_query("insert into nn values ('  ','$image1','','')"); 

      echo "<img src='test_uploads/$image1'>"; 
      } else 
       { echo "move_uploaded_file function failed for ".$name_array[$i]."<br>"; 
      } 
      } 
      } 
      ?> 

在数据库表NN有此列。 id - image1 - image2 - image3。 谢谢

+1

这看起来可怕,不安全,因为你的用户参数不[正确转义(HTTP://鲍比桌。 COM/PHP)。您应该**绝不**将'$ _POST'数据直接放入查询中。这造成了一个巨大的[SQL注入漏洞](http://bobby-tables.com/)。另外,'mysql_query'是一个过时的接口,不应该被使用,它将被从PHP中删除。像[PDO这样的现代化替代品并不难学](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/)。像[PHP The Right Way](http://www.phptherightway.com/)这样的指南解释了最佳实践。 – tadman 2014-11-03 19:56:12

回答

0

让我们来清理一下。

让我们设置数据库连接。在这个例子中,我们正在转向mysqli。然后我们将处理移动文件,并将文件路径存储在数据库中。

$conn = new mysqli('host', 'user', 'pass', 'db'); 

if(isset($_FILES['file_array'])): 
    $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : false; 
    if($id): 
     $file_array = $_FILES['file_array']; 
     for($i = 0; $i < count($file_array['tmp_name']); $i++): 
      if(move_uploaded_file($file_array['tmp_name'][$i], 'test_uploads/'.$file_array['name'][$i])): 
       $stmt = $conn->prepare("insert into nn values('', ?, '', '')"); 
       $stmt->bind_param('s', $file_array['name'][$i]); 
       if($stmt->execute()): 
        echo $file_array['name'][$i].' has been uploaded successfully.'; 
       else: 
        echo 'Failed to upload '.$file_array['name'][$i].'. Please check the file and try again!'; 
        return false; 
       endif; 
      endif; 
     endfor; 
    endif; 
endif; 

没有理由创建所有那些凌乱的变量。我们已经迁移到了MySQLI,它现在支持,并且我们已经使用了一个准备好的语句来确保图像的名称不是恶意的,可能对我们的应用程序不利。

资源