【问题标题】:PHP uploading multiple files and save their path into a single row in DBPHP上传多个文件并将它们的路径保存到数据库中的一行
【发布时间】:2016-10-27 14:50:11
【问题描述】:

我环顾四周,没有找到适合我需要的解决方案。 所以让我们切入正题。

场景:用户将填写一些文本表单,这些表单的输入将存储到数据库表中(文本输入正常工作并存储到数据库中就好),用户将以相同的形式上传 7 个文件和文件的路径将存储在同一个表中的不同列中,例如 image1 image2 image3 等,但在同一行中,因此当需要该行的 id 时,文件路径也将被检索但我无法构建查询将路径插入数据库,我只管理存储一个文件并将其路径存储到数据库中,但我正在努力处理多个文件,我只是不知道如何检查 for 循环是否已完成以及如何构建查询以插入所有更新文件的路径在各自的列中合并为一行。

服务器正在运行 PHP 和 postgreSQL

在此先感谢您,希望您能帮助我!

  <?php
  include '../include/dbase.php';
  $result = '';
  if (isset($_FILES['upload'])) {
   $nombre = $_FILES['upload']['name'];
   $ntemporal = $_FILES['upload']['tmp_name'];
   $tipo = $_FILES['upload']['type'];
   $tamaño = $_FILES['upload']['size'];
   $error = $_FILES['upload']['error'];
   $file_name_all = '';
    for($i=0; $i<count($_FILES['upload']['name']); $i++)
     {
        $tmpFilePath = $_FILES['upload']['tmp_name'][$i];
           if ($tmpFilePath != "")
             {
               $path = "../imagenes/propiedades/";
               $name = $_FILES['upload']['name'][$i];
               $size = $_FILES['upload']['size'][$i];

               list($txt, $ext) = explode(".", $name);
               $file= time().substr(str_replace(" ", "_", $txt), 0);
               $info = pathinfo($file);
               $filename = $file.".".$ext;
               if(move_uploaded_file($_FILES['upload'['tmp_name'][$i],   $path.$filename))
               {
                  //my guess is an if check here to see if for 
         loop has finished all the uploads, and if returns true a try and 
      catch with the sql query to upload  only the path of each file the 
       row containing all other user input text.
               }
         }
           }
           }
          ?>

【问题讨论】:

    标签: php sql postgresql for-loop


    【解决方案1】:

    最好将文件保存在类似 files/$id_user/.. 的目录中以及数据库中的名称。

    您可以为文件制作表格; 例如带有 id_user + file_name 的表文件。

    如果你想全部在同一个表中,你可以把所有文件名用逗号或;分隔。并在选择它们并分解后将它们放入数组中..

    在您的代码中,最好使用 ' 而不是 ",因为 php 会尝试在 " " 中查找变量 .. 并且白白浪费时间...

    $filename = $file.'.'.$ext; $filename = $file.".".$ext;;
    

    如果你写:

    $test = 'hello';
    echo 'i tell you $test'; => i tell you $test
    echo "i tell you $test"; => i tell you hello
    

    【讨论】:

    • 感谢您的建议,我以前使用“”而不是“”,发现在使用变量时使用串联更容易,有时我在构建需要“”的查询时会感到困惑。感谢您的建议,但我正在寻找一种将文件路径放在不同列中的方法。
    • 因此,在您的表格中,您可以为 X 文件创建 X 列。并保存每个文件或文件名。
    【解决方案2】:

    在您的表中,创建列 file_0, file_1, .... 之后,您可以像这样保存在表格中:

    if(move_uploaded_file($_FILES['upload'['tmp_name'][$i],   $path.$filename))
               {
              $sql = "UPDATE `your_table` SET `file_$i` = '$path.$filname' WHERE `id` = '$id_user'";
    //execute your $sql
               }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 2015-08-12
      • 1970-01-01
      • 2017-09-25
      • 2015-04-20
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多