php - 使用 PDO 通过单个查询插入多行

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

最佳答案

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

关于php - 使用 PDO 通过单个查询插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19627423/

相关文章:

php - 如何创建等级系统

PHP Mysql 准备查询按照日期排序

SQL 查询返回两个字符串是否包含共享术语

sql - 根据其他表中的两个日期选择值?

c++ - 在C++中修改PL/SQL语句字符串

php - 从一个类别中的两种帖子格式查询帖子

php - 在php中动态构建一个数组

php - Zend 框架关系与表选择

php - 使用 Twitter API 向关注者发送批量直接消息

mysql - 类似于 MSSQL 的 MySQL Profiler 程序