插入多行使用PDO单查询(Inserting multiple rows with a single

2019-10-30 04:14发布

我已经切换到PDO时遇到麻烦构建和执行一个SQL查询,将插入多行只有一个执行。

内容$data json_decode后:

Array (
    [action] => load
    [app] => CA
    [street_type] => AVE
    [place_type] => --
    [state] => AL
)

码:

$data = json_decode(file_get_contents("php://input"));
$query = "REPLACE INTO tblsettings(setApp, setIP, setKey, setValue)VALUES";
$qPart = array_fill(0, count($data), "(?, ?, ?, ?)");
$query .= implode(",", $qPart);
$stmt = $db->prepare($query);

    foreach($data as $key => $val){
        $query = "REPLACE INTO tblsettings(setApp, setIP, setKey, setValue)VALUES";
        $qPart = array_fill(0, count($data), "(?, ?, ?, ?)");
        $query .= implode(",", $qPart);
        $stmt = $db->prepare($query);

        $i = 1;
        if(!is_array($val)){
            $stmt->bindParam($i++, $data->app);
            $stmt->bindParam($i++, gethostbyname(trim(gethostname())));
            $stmt->bindParam($i++, $key);
            $stmt->bindParam($i++, $val);
        }

        if ($stmt->execute()){
            echo "Success";
        }else{
            echo $stmt->errorCode();
        }
    }

Answer 1:

我想$i = 1; 应该是内部for循环,外面if循环,因为每一个for循环,将通过4递增,这是我们不希望我们,想从1开始,达到4和出口,每for

 $data = json_decode(file_get_contents("php://input"), true);
 $query = "REPLACE INTO tblsettings(setApp, setIP, setKey, setValue)VALUES";
 $qPart = array_fill(0, count($data), "(?, ?, ?, ?)");
 $query .= implode(",", $qPart);
 $stmt = $db->prepare($query);

 foreach($data as $key => $val){
   $i = 1; //for every for loop reset it to 1
   if(!is_array($val)) {
      $stmt->bindParam($i++, $data->app); //here it will be 1
      $stmt->bindParam($i++, gethostbyname(trim(gethostname())));  //here it will be 2
      $stmt->bindParam($i++, $key);  //here it will be 3
      $stmt->bindParam($i++, $val);  //here it will be 4
   }
  }

  if ($stmt->execute()){
        echo "Success";
   }else{
        echo $stmt->errorCode();
   }


文章来源: Inserting multiple rows with a single query using PDO