使用PDO使用单个查询插入多行

时间:2013-10-28 04:57:10

标签: php mysql sql arrays pdo

我已切换到PDO,但在构建和执行SQL查询时遇到问题,该查询只插入一行就会插入多行。

json_decode之后$data的内容:

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();
        }
    }

1 个答案:

答案 0 :(得分:0)

我猜$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();
   }