如何为每个循环使用单个多个数组来更新单个sql语句

时间:2016-03-15 10:48:30

标签: php sql for-loop

我想为两个数组使用单个。

数组1:具有图像路径(路径根据用户需要是动态的)

数组2:具有每个图像的值描述字段(描述根据用户需要是动态的)

我想只使用一个sql语句在sql表中插入两个数组。

<?php $sql="INSERT INTO posts(title,description,category,createdBy,pictureURL,CreatedAt) VALUE ('$title',
                '$description','$category','$creatdby','Admin/PostImages/$finalpath',now());"; 
                $result = mysqli_query($conn,$sql);
                if($result)
                {

                     $upload_directory = 'PostImages/';                      
                      $field_values_array = $_REQUEST['desc'];
                          $x=0;  
                          foreach($field_values_array as $value1){
                          foreach ( $_FILES['photo']['name'] AS $key => $value ){
                               //Move file to server directory
                               if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory . $_FILES["photo"]["name"][$x])){
                               $finalpath=$upload_directory . $_FILES["photo"]["name"][$x];
                               }
                               if (isset($_SESSION['p_id'])){
                        $p_id = $_SESSION["p_id"];
                        }
                              $sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) VALUES ('$p_id','$value1','$finalpath')"; 
                                  $result1 = mysqli_query($conn,$sql1);                 
                              $x++;  
                          }
                    }       
                        header("Location: uploadpost_test.php");                        

                }
                else
                {
                    echo "Error: " . $sql . "<br>" . $conn->error;
                } ?>

1 个答案:

答案 0 :(得分:0)

我重构并清理你的代码。试试这个。

                    if(isset($_SESSION['p_id']))
                    {
                        $p_id = $_SESSION["p_id"];
                    }
                    $values = '';
                    $next = ',';
                    $len = count($field_values_array);
                    foreach($field_values_array as $x=>$value1)
                    {

                        if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory.$_FILES["photo"]["tmp_name"][$x]))
                        {
                           $tmp_name = $_FILES["photo"]["tmp_name"][$x];
                           $finalpath = $upload_directory.$tmp_name;
                           $next = $x >= $len-1 ? '' : $next;
                           $values .= "VALUES('$p_id','$value1','$finalpath')".$next;
                        }
                    }
                    $sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) $values"; 
                    $result1 = mysqli_query($conn,$sql1);