php在for循环中将数据插入sql

标签 php mysql

我想在 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

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

最佳答案

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

关于php在for循环中将数据插入sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35693252/

相关文章:

javascript - 从 php 中获取 () json

php - 这是在 MySQL 中获取记录的最快方法吗

php - 为什么我下载的文件总是损坏或损坏?

php - 删除行时如何在mysql自动递增字段中保持正确的数字顺序

php - 如何使用左连接选择涉及当前用户的对话

php - 这是这个数据库设计的正确方法

PHP 常量 SQL 查询

mysql - MYSQL 中的正则表达式错误

mysql - 是否可以在 MySQL 中对行进行两次分组?

mysql - Sql 触发器条件检查不起作用