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