I have the following SQL query which is performed via an AJAX server request on form submission. It checks a form POST variable $product for any associated products in the database limiting the results to 2. I need to be able to uniquely identify each result from the query using PHP and store them in variables as $product1 and $product2, then return these values to the form without page refresh. Why are the PHP SQL query results not automatically assigned a unique key in the associative array? (see image below)
$product = $_POST['product'];
$sql_query3 = "Select tbl_mixed_case.related_product
FROM tbl_mixed_case JOIN tbl_product_info
ON tbl_product_info.id = tbl_mixed_case.prod_code_id
AND tbl_product_info.product + ' ' = '$product' LIMIT 2" ;
$result3 = mysqli_query($dbconfig, $sql_query3);
while ($products = mysqli_fetch_array($result3, MYSQL_ASSOC)) {
print_r(array_values($products));
}
Try the following:
$product = $_POST['product'];
$sql_query3 = "Select tbl_mixed_case.related_product
FROM tbl_mixed_case JOIN tbl_product_info
ON tbl_product_info.id = tbl_mixed_case.prod_code_id
AND tbl_product_info.product + ' ' = '$product' LIMIT 2" ;
$result3 = mysqli_query($dbconfig, $sql_query3);
var $dispProd
while ($products = mysqli_fetch_array($result3, MYSQL_ASSOC)) {
$dispProd[] = $products;
}
header('Content-Type: application/json');//add the proper header
echo json_encode(['products'=>$dispProd]);//convert to json
in your ajax success function you do the following:
success:function(data) {
$('#product1').val(data.products[0]);//add the first value to a input with the id of product1
$('#product2').val(data.products[1]);
}
I have included the ajax request and form input below:
function submitdata() {
var product = document.getElementById("product").value;
// Returns successful data submission of associated products
var dataString = 'product=' + product;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "product.php",
data: 'application/json; charset=utf-8',
cache: false,
success: function(data) {
alert(data);
$('#product1').val(data.products[0]);//add the first value to a input with the id of product1
$('#product2').val(data.products[1]);
}
});
}
<input type="text" value="" placeholder="" class="" id="product1" name="product1" tabindex="-1"/>
<input type="text" value="" placeholder="" class="" id="product2" name="product2" tabindex="-1"/>