每个坏插入在一个forech中有两个变量



你好,我的代码有问题。

我有HTML与JS:

$(document).ready(function () {

// allowed maximum input fields
var max_input = 5;

// initialize the counter for textbox
var x = 1;

// handle click event on Add More button
$('.add-btn').click(function (e) {
e.preventDefault();
if (x < max_input) { // validate the condition
x++; // increment the counter
$('.wrapper').append(`
<div class="input-box">
<input type="text" name="input_name[]"/>
<input type="text" name="input_price[]">
<a href="#" class="remove-lnk">Remove</a>
</div>
`); // add input field
}
});

// handle click event of the remove link
$('.wrapper').on("click", ".remove-lnk", function (e) {
e.preventDefault();
$(this).parent('div').remove();  // remove input field
x--; // decrement the counter
})

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="input-box">
<input type="text" name="input_name[]">
<input type="text" name="input_price[]">
<button class="btn add-btn">+</button>
</div>
</div>

和我需要在数据库中插入所有输入(名称和价格)现在如果我尝试只插入第一行

php脚本:这是一个函数,$ id_produckt是从url获取的。

if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){ 


$input_name = $_POST["input_name"]; 
$input_price = $_POST["input_price"]; 


foreach (array_combine($input_name, $input_price) as $field_name => $field_price){
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $field_name, $field_price);

$result = db_query($sql, $data);
return $result;
}

}

你能帮我吗?我累了

我让函数像那样工作。

function insertVariantsProduct($id_produkt){  
$userData = count($_POST["input_name"]);
if ($userData > 0) {
for ($i=0; $i < $userData; $i++) { 
if (trim($_POST['input_name'] != '') && trim($_POST['input_price'] != '')) {

$var_id = $_POST["input_id"][$i];
$name   = $_POST["input_name"][$i];
$price  = $_POST["input_price"][$i];
if(empty($var_id) && !isset($var_id)){      
$sql = "INSERT INTO variant_product ( id_product, name, price ) VALUES(?,?,?)";
$data = array("isi", $id_produkt, $name, $price);
}else {
$sql = "UPDATE variant_product SET name='$name',price='$price' WHERE id='$var_id'  ";
$data = null;
}
$result = db_query($sql, $data);

}
}
return $result; // This should be out of loop because it's will break the loop 
}

}

最新更新