在php中运行两个选择查询并将其编码为json格式

时间:2018-07-05 13:00:30

标签: php json ajax

如何通过一个AJAX调用和PHP函数返回两个JSON对象?

这是HTML:

// bootstrap modal 
<div id="paymentViewModal" class="modal fade">
    <form method="POST" id="update_payment">
        <input type="text" class="totalAmount"  id="totalAmount">
        <br>
        <input type="text" class="pdAmount" id="pdAmount"> 
    </form>
</div>  

还有Jquery:

$(document).on('click', '.payment_data', function() {
var pymnt_id = $(this).val();
$.ajax({
    url:"sum_total.php",
    method:"POST",
    data:{pymnt_id:pymnt_id},
    dataType:"json",
    success:function(data){
        // textboxt totalAmount
        $('#totalAmount').val(data.total_order_value); 
        //textbox pdAmount 
        $('#pdAmount').val(data.paid_total);  
        $('#paymentViewModal').modal('show');
    }
   });
});

第一个查询的结果非常理想,但是我要执行两个查询

// sum_total.php
if(isset($_POST["pymnt_id"]))
{

$query =  mysqli_query($conn, "SELECT SUM(sub_total) AS total_order_value FROM tbl_order2
WHERE order_customer_id = '".$_POST["pymnt_id"]."'
");
$row = mysqli_fetch_array($query);  

// if i run only one query its work fine
// want to get result from both tables
$query = "SELECT SUM(payment_amount) AS paid_total FROM payments
WHERE customer_id = '".$_POST["pymnt_id"]."'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
}
echo json_encode($row);
?>

2 个答案:

答案 0 :(得分:1)

您正在重写$row,因此旧数据将被覆盖。考虑做这样的事情:

此外,考虑使用PDO准备的语句

注意:未经测试的代码

// sum_total.php
if(isset($_POST["pymnt_id"]))
{
$output = [];
// use prepared statements to prevent SQL injection
$query =  $conn->prepare($conn, "SELECT SUM(sub_total) AS total_order_value FROM tbl_order2
WHERE order_customer_id = ?
"); 
$query->exec($_POST["pymnt_id"]);
$output["row1"] = $query->fetch();  

// if i run only one query its work fine
// want to get result from both tables
$query = "SELECT SUM(payment_amount) AS paid_total FROM payments
WHERE customer_id = ?";
$query->exec($_POST["pymnt_id"]);
$output["row2"] = $query->fetch();
// echo inside the if statement
echo json_encode($output);
}

希望有帮助

答案 1 :(得分:0)

将行添加到and数组中,然后回显整个数组。

// sum_total.php
if(isset($_POST["pymnt_id"]))
{
    $output = array();

    $query =  mysqli_query($conn, "SELECT SUM(sub_total) AS total_order_value FROM tbl_order2
    WHERE order_customer_id = '".$_POST["pymnt_id"]."'
    ");
    $row = mysqli_fetch_array($query);  
    $output['row1'] = $row;

    // if i run only one query its work fine
    // want to get result from both tables
    $query = "SELECT SUM(payment_amount) AS paid_total FROM payments
    WHERE customer_id = '".$_POST["pymnt_id"]."'";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_array($result);
    $output['row2'] = $row;

}
    echo json_encode($output);
?>