I have store labels and numeric values of same form in two arrays, pass these arrays using AJAX to php. now I want to store each array in two different fields of the same table 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 file
$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));
}
the problem is, it does not inserted values parrallel. first it insert values in category field with 0 under value field. the filled value field with blank categories name.