两个文件的JSON格式错误

时间:2013-04-29 18:22:51

标签: php json parsing formatting

我想知道,我刚刚创建了我的数据表,但其中两个正在给出JSON格式错误。我正在这两个表中连接两个表。我尝试在phpmyadmin中运行查询,它运行得很好以下是我的服务器端文件的一个示例:

<?php
$username="drup197";
$password="*****";
$database="census";
$server="localhost";

$link = mysqli_connect($server,$username,$password,$database);

//@mysql_select_db($database,$link) or die( "Unable to select database");
$query = "
    SELECT *   
    FROM national_age_gender_demographics INNER JOIN arizona_age_gender_demogrpahics
    WHERE national_age_gender_demographics.age_group = arizona_age_gender_demogrpahics.age_group
    ORDER BY national_age_gender_demographics.index_number";

$result = mysqli_query($link,$query);

if(!$result)  die( "Query: " . $query . "\nError:" . mysql_error() );

//print_r($row);
$tableData = '{"aaData": [[';
$numRows = $result->num_rows;
$row = mysqli_fetch_array($result);

for ($i = 0; $i < $numRows; $i++) {
    if ($i != 0) {
        $tableData .= ",[";
    }
    $tableData .= '"' . $row['age_group'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.both_pop'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.male_pop'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.female_pop'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.male_percent'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.female_percent'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.both_percent'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.males_per_100_females'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.both_pop'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.male_pop'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.female_pop'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.male_percent'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.female_percent'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.both_percent'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.males_per_100_females'] . '"]';
    if ($i != $numRows - 1) {
        $row = mysqli_fetch_array($result);
    }
}
$tableData .= ']}';
echo $tableData;
?>

有谁知道这里有什么问题?

1 个答案:

答案 0 :(得分:0)

首先,史蒂文是对的,最好使用json编码(或至少更整洁)来创建你的json,让你远离凌乱的ifs和支架业务。

我还建议使用mysqli_fetch_assoc而不是使用mysqli_fetch_array,正如您当前指定的那样,它应返回关联和编号结果(请参阅此处http://php.net/manual/en/mysqli-result.fetch-array.php),这可能会影响您的结果。

例如:

...
$row = mysqli_fetch_assoc($result);
$json_data = json_encode($row);
echo $json_data;
?>

尝试一下,看看你如何上场?