我在两个数组中存储了相同形式的标签和数值,使用AJAX将这些数组传递给php。现在我想将每个数组存储在同一个表mysql的两个不同字段中。
var arr = [];
var arr1 = [];
$('.cat').each(function() {
arr.push($(this).text());
});
$('.cat_value').each(function() {
arr1.push($(this).val());
});
$.ajax({
url:'rs_insert.php',
data:{categories: arr, cat_values:arr1},
type:'POST',
success:function() {
alert("data has been sent");
document.getElementById('exampleModal1').style.display = "none";
}
});

php文件
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$values = array();
foreach($_POST['categories'] as $key => $name) {
$values[] = $name;
}
$sql1 = "INSERT INTO rs (Category) VALUES ";
foreach($values as $cat) {
$sql1 .= "('" . $cat . "'),";
}
$sql1_trimmed = rtrim($sql1,',');
////
$values1 = array();
foreach($_POST['cat_values'] as $key => $value) {
$values1[] = $value;
}
$sql2 = "INSERT INTO rs (Value) VALUES ";
foreach($values1 as $val) {
$sql2 .= "('" . $val . "'),";
}
$sql2_trimmed = rtrim($sql2,',');
if (!mysqli_query($con,$sql1_trimmed)) {
die('Error: ' . mysqli_error($con));
}
if (!mysqli_query($con,$sql2_trimmed)) {
die('Error: ' . mysqli_error($con));
}

答案 0 :(得分:2)
你可以试试这个:
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$values = array();
foreach($_POST['categories'] as $key => $name) {
$values[] = $name;
}
////
$values1 = array();
foreach($_POST['cat_values'] as $key => $value) {
$values1[] = $value;
}
$sql1 = "INSERT INTO rs (Category,Value) VALUES ";
for($i=0;$i<count($values);$i++) {
$sql1 .= "('" . $values[$i] . "','". $values1[$i] ."'),";
}
$sql1_trimmed = rtrim($sql1,',');
if (!mysqli_query($con,$sql1_trimmed)) {
die('Error: ' . mysqli_error($con));
}