在json中加入多个表

时间:2015-04-07 03:00:32

标签: php mysql json join

当我想通过json文件显示数据时,我遇到了问题。如果我在一个表中显示数据就可以了,但是当我想连接多个表时没有显示数据

<?php
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);

 $query = "SELECT Product.Product_Name, Product.Price, Product.Image, Gender.Description, Age.Description, Status.Availability  from Product join Age on Age.Age_ID join Gender on Gender.Gender_ID join Status on Status.ID";

$result = mysql_query($query);

//Create an array
    $json_response = array();

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $row_array['Product_Name'] = $row['Product_Name'];
        $row_array['Price'] = $row['Price'];
        $row_array['Image'] = base64_encode($row["Image"]);
        $row_array['Description'] = $row['Description'];
        $row_array['Description'] = $row['Description'];
        $row_array['Availability'] = $row['Availability'];



        //push the values in the array
        array_push($json_response,$row_array);
    }
    echo json_encode($json_response);

    //Close the database connection
    fclose($db)
?>

1 个答案:

答案 0 :(得分:0)

您的上一次加入on Status.ID就是问题所在。 Status表格没有ID列。根据您的图表,您有Status.Status_ID(您没有Status.ID)此外,您的数据必须包含相关数据,其中每个表都有共同的值,否则,您将获得空结果

你的图表:

enter image description here

更改您的查询

SELECT 
    Product.Product_Name,
    Product.Price,
    Product.Image,
    Gender.Description,
    Age.Description,
    Status.Availability
FROM
    Product
JOIN
    Age ON Age.Age_ID
JOIN
    Gender ON Gender.Gender_ID
JOIN
    Status ON Status.ID

SELECT 
    Product.Product_Name,
    Product.Price,
    Product.Image,
    Gender.Description,
    Age.Description,
    `Status`.Availability
FROM
    Product
JOIN
    Age ON Product.Age_ID = Age.Age_ID
JOIN
    Gender ON Product.Gender_ID = Gender.Gender_ID
JOIN
    `Status` ON Product.Status_ID = `Status`.Status_ID