gpt4 book ai didi

php - 如何在每个循环内将数组的值写入mysql表?

转载 作者:行者123 更新时间:2023-11-29 07:31:05 27 4
gpt4 key购买 nike

我已经通过post方法收到了一些数据,我将数据写入数组,现在我如何将数据写入mysql表?数据接收示例如下所示。我不断收到此错误:错误,查询失败

if (isset($_POST['submit'])) {
$data = [];
foreach($_POST['checkbox'] as $rowNum) {
$data[] = explode("::", $_POST['opt'][$rowNum]);
}
var_dump($data);

$sku =$data[$rowNum][0];
$description =$data[$rowNum][1];
$location =$data[$rowNum][2];
$quantitydate =$data[$rowNum][3];

$link = mysqli_connect("somesite", "****", "*******", "******");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

$query ="SELECT * FROM Test WHERE sku = '$sku'";
$testResult = mysqli_query($link, $query) or die('Error, query failed');

if(mysqli_fetch_array($testResult) == NULL){
$sql = "INSERT INTO test (ID, sku, description, location, quantitydate) VALUES ('$ID','$sku', '$description','$location', '$quantitydate',NOW())";
if(mysqli_query($link, $sql)){
echo "Records added successfully.<br /><br />";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// close connection
mysqli_close($link);
}else
{
echo "Record Already Exist<br /><br />";
}
}

输出示例:

// Output sample (selected row 2 and 4):
array (size=2)
0 =>
array (size=4)
0 => string 'SKU2' (length=4)
1 => string 'DESC2' (length=5)
2 => string 'LOC2' (length=4)
3 => string 'QUAN2' (length=5)
1 =>
array (size=4)
0 => string 'SKU4' (length=4)
1 => string 'DESC4' (length=5)
2 => string 'LOC4' (length=4)
3 => string 'QUAN4' (length=5)

最佳答案

使用准备好的语句:

$stmt = mysqli_prepare($link, "INSERT IGNORE INTO tableName (sku, description, location, quantitydate) VALUES (?, ?, ?, ?)";
mysqli_stmt_bind_param($stmt, "ssss", $sku, $desc, $location, $quantitydate);
foreach ($_POST['checkbox' as $rowNum) {
$row = explode('::', $_POST['opt'][$rowNum]);
$sku = $row[0];
$description = $row[1];
$location = $row[2];
$quantitydate = $row[3];
mysqli_stmt_execute($stmt);
if (mysqli_affected_rows($stmt) == 0) {
echo "SKU $sku already exists <br/><br/>";
}
}

如果 sku 列上有唯一索引,则无需先执行 SELECT 查询。 INSERT IGNORE 将简单地忽略添加重复行的尝试,并且 mysqli_affected_rows 将返回 0 以指示未插入任何内容。

关于php - 如何在每个循环内将数组的值写入mysql表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32642121/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com