PHP - 在mySQL数据库上查询并在以JSON格式显示结果时失败

时间:2017-07-14 14:04:51

标签: php mysql json

所以我们最近为我们大学的一个项目建立了一个mySQL数据库,目前正在研究用php编写的数据访问文件。为了使用我们前端的数据,我们需要将其格式化为JSON。虽然在某个对象的结果中放置一个对象数组正在工作,但它不能使用2个对象数组。 工作代码:

<?php
include_once 'db.php';

$email = "email@online.com";

$conn = connect();
$conn->set_charset('utf8');

$resultArr = array();
$sql = "SELECT * FROM `customer` WHERE email = '$email'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    $resultArr['customer'][$row['email']] = array('email' => $row['email'], 'address' => $row['address']);

    $sql2 = "SELECT id, name, address FROM shop INNER JOIN rel_shop_customer WHERE customer_email='".$row['email']."' AND rel_shop_customer.shop_id = shop.id";
    $result2 = $conn->query($sql2);
    while($row2 = $result2->fetch_assoc()) {
        $resultArr['customer'][$row['email']]['shops'][] = $row2;
    }

}
$resultArr['customer'] = array_values($resultArr['customer']);
} else {
echo "failure";
}
echo json_encode($resultArr, JSON_UNESCAPED_UNICODE);

?>

这是不可行的代码:

<?php
include_once 'db.php';

$email = "email@online.com";

$conn = connect();
$conn->set_charset('utf8');

$resultArr = array();
$sql = "SELECT * FROM `customer` WHERE email = '$email'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    $resultArr['customer'][$row['email']] = array('email' => $row['email'], 'address' => $row['address']);

    $sql2 = "SELECT id, name, address FROM shop INNER JOIN rel_shop_customer WHERE customer_email='".$row['email']."' AND rel_shop_customer.shop_id = shop.id";
    $result2 = $conn->query($sql2);
    while($row2 = $result2->fetch_assoc()) {
        $resultArr['customer'][$row['email']]['shops'][] = $row2;
    }

    $sql3 = "SELECT img, name FROM ad INNER JOIN rel_customer_ad WHERE customer_email='".$row['email']."' AND rel_customer_ad.ad_name = ad.name";
    $result3 = $conn->query($sql3);
    while($row3 = $result3->fetch_assoc()) {
        $resultArr['customer'][$row['email']]['ads'][] = $row3;
    }
}
$resultArr['customer'] = array_values($resultArr['customer']);
} else {
   echo "failure";
}
echo json_encode($resultArr, JSON_UNESCAPED_UNICODE);

?>

两个SQL查询在直接在数据库上运行时提供了预期的结果,我不知道为什么第二个在PHP脚本中不能工作。

0 个答案:

没有答案