我有以下SQL查询,它是通过表单提交上的AJAX服务器请求执行的。它检查数据库中任何相关产品的表单POST变量$ product,将结果限制为2.我需要能够使用PHP唯一地识别查询中的每个结果,并将它们存储在变量中作为$ product1和$ product2,然后返回这些值没有页面刷新的形式。 为什么PHP SQL查询结果不会在关联数组中自动分配唯一键? (见下图)
$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));
}
答案 0 :(得分:1)
尝试以下方法:
$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
在您的ajax成功函数中,您执行以下操作:
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]);
}
我在下面包含了ajax请求和表单输入:
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"/>