【问题标题】:php INSERT data to sql in for loop [duplicate]php在for循环中向sql插入数据[重复]
【发布时间】:2016-06-12 02:53:13
【问题描述】:

我想在 for 循环中创建一个 mysql 插入语句。 I'm looking for to insert multiple records at a time.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$label =htmlspecialchars( $_POST["label"]);
$splitLabel = explode(" ", $label);//split the label to a array
}
//.....insert another data, getting the $last_id here

$sql = $result = "";
for ($i =0; $i< count($splitLabel); $i++){
    if ($i < count($splitLabel)){
        $sql .= "INSERT INTO label (item_id, label)
        VALUES ('".$last_id."', '".$splitLabel[$i]."');";
    }else{
        $sql .= "INSERT INTO label (item_id, label)
        VALUES ('".$last_id."', '".$splitLabel[$i]."')";
    }
}
$result = mysqli_query($conn, $sql);

我有一个错误

 check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO label (item_id, label)
    VALUES ('13', 'tin');INSERT INTO label (' at line 2

标签表:

Field      Type           null
item_id    int(11)         NO
label      varchar(50)     NO

我找不到错误,请帮我找到它..

【问题讨论】:

  • 标签表没有'PRIMARY KEY'
  • mysqli_query() 执行 one 语句。但是例如INSERT ... ; INSERT ...; 是两个语句。见docs.php.net/manual/en/mysqli.quickstart.multiple-statement.php |但究竟为什么你需要多个语句,尤其是。当他们都打同一张桌子时?
  • 使用mysqli_multi_query执行多个查询
  • 在你的情况下,只有条件才会执行。为什么要写 if 和 else??
  • 我想在 for 循环中将多条记录插入 MySQL....

标签: php mysql


【解决方案1】:

mysqli_query() 只执行一个语句,但您要发送多个语句。你可以使用mysqli_multi_query(),但是......

最好使用prepared statement + parameters
比如像

if ( isset($_POST["label"]) ) {
    $stmt = $conn->prepare('INSERT INTO label (item_id, label) VALUES (?,?)')
    if ( !$stmt ) {
        someErrorHandler( $conn->error );
    }
    else if ( !$stmt->bind_param('ss', $last_id, $label) ) {
        someErrorHandler( $stmt->error );
    }
    else {
        // I have no idea where this $last_id comes from ....
        foreach( explode(' ', $_POST["label"]) as $label ) {
            if ( !$stmt->execute() ) {
              someErrorHandler( $stmt->error );
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    您只需使用mysqli_multi_query() 进行多个查询。

    $sql = "";
    $result = "";
    
    for ($i =0; $i< count($splitLabel); $i++){
        if ($i < count($splitLabel)){
            $sql .= " INSERT INTO label (item_id, label)
            VALUES ('".$last_id."', '".$splitLabel[$i]."');";
        }else{
            $sql .= " INSERT INTO label (item_id, label)
            VALUES ('".$last_id."', '".$splitLabel[$i]."');";
        }
    }
    $result = mysqli_multi_query($conn, $sql);
    

    您不能使用多个 INSERT 到单个 mysqli_query 执行此操作,您可以使用 mysqli_multi_query() 执行多个查询。

    【讨论】:

      【解决方案3】:

      对于多个查询执行,您可以使用mysqli_multi_query()

      对于单个查询的表的多插入是这样的multi insert:-

      INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
      

      所以你可以试试

      $sqlInsert   = '';
      $countOfData = count($splitLabel);
      for ($i = 0; $i < $countOfData; $i++){
          $sqlInsert .= "('{$last_id}', '{$splitLabel[$i]}'),";
      }
      $sqlInsert = rtrim($sqlInsert, ',');//remove the extra comma
      if ($sqlInsert) {
          $sql = "INSERT INTO label (item_id, label) VALUES {$sqlInsert} ;";
          $result = mysqli_query($conn, $sql);
      }
      

      【讨论】:

        【解决方案4】:

        试试这个代码

        if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $label =htmlspecialchars( $_POST["label"]);
        $splitLabel = explode(" ", $label);//split the label to a array
        }
        //.....insert another data, getting the $last_id here
        
        $sql = $result = "";
        for ($i =0; $i< count($splitLabel); $i++){
        if ($i < count($splitLabel)){
            $sql .= "INSERT INTO label (item_id, label) VALUES ('$last_id', '$splitLabel[$i]')";
        }else{
            $sql .= "INSERT INTO label (item_id, label)
            VALUES ('$last_id', '$splitLabel[$i]')";
        }
        }
        

        【讨论】:

          【解决方案5】:
              $sql .= "INSERT INTO label (item_id, label)
              VALUES ('".$last_id."', '".$splitLabel[$i]."');";
          

          你错过了“;”

          【讨论】:

          • 用“;”试试就知道了。
          • @kingyau 总是用 ; 来结束你的陈述。 - 它是语法分隔符,没有其他方法......不要忘记,您正在使用 for 循环连接多个字符串。尝试在执行之前回显您的 $sql 以查看查询过程中的确切内容。顺便说一句,像其他人建议的那样,使用 mysqli_multi_query() 来执行这种查询或考虑使用 PDO->query (女巫允许多查询),并且在插入同一个表时不需要多个查询;您可以使用一个 INSERT 命令将数千行插入到同一个表中(请参阅文档)。
          • @Wh1T3h4Ck5 你能为这个问题推荐一些文档吗?
          • @kingyau 对于所有 php/mysql 开发人员来说,最好的资源是 php.netmysql.com。您的问题可以使用this link 解决(很可能)。一般来说,在那里你可以找到正确学习php和mysql所需的一切。
          【解决方案6】:

          试试这个。

             $sql = $result = "INSERT INTO label (item_id, label) VALUES ";
             for ($i =0; $i< count($splitLabel); $i++){    
                  $sql .= "('".$last_id."', '".$splitLabel[$i]."')";
                  if ($i < count($splitLabel) - 1){
                      sql .= ",";
                  }
              }
          

          【讨论】:

          • 他想一次插入多个值
          • 他正在使用 mysqli。你能为mysqli多插入准备样品吗?所以你得到 +ve 投票。
          • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。 - From review
          猜你喜欢
          • 1970-01-01
          • 2021-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-30
          • 1970-01-01
          • 2017-10-24
          • 1970-01-01
          相关资源
          最近更新 更多