1

我想知道,我刚刚创建了我的数据表,但其中两个给出了 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;
?>

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

4

1 回答 1

0

首先 Steven 是对的,最好使用 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;
?>

试试看,看看你的进展如何?

于 2013-04-29T19:22:22.117 回答