doutuo6689 2013-06-13 15:31
浏览 62
已采纳

通过php和jquery post返回并解析json数组

I'm trying to return a json array of names pulled from my database. I'm not sure what I'm missing here, but it never gets to the alert call. The returned data doesn't have to be json, I was just trying that approach first. It completes the INSERT call and I know that it is returning the correct data set. What's wrong with my code?

Javascript

function showDB() {
    $.post('example.php', $('#infoForm').serialize(), function(data) {  
        var json = $.parseJSON(data);
        $.each(json, function(i, item) {
            alert(item);
        });
    }, "json");
}

PHP

<?php
    $host = "www.host.com";
    $user = "user";
    $pwd = "password";
    $db = "exampleDB";

    $conn = mysqli_connect($host, $user, $pwd)or die("Error connecting to database.");
    mysqli_select_db($conn, $db) or die("Couldn't select the database."); 

    $name = $_POST['name'];
    $color = $_POST['color'];   
    $nameArray = array();

    $stmt = mysqli_stmt_init($conn);
    $query = "INSERT INTO people VALUES (?, ?)";
    mysqli_stmt_prepare($stmt, $query) or die("Failed to prepare statement.");
    mysqli_stmt_bind_param($stmt, "ss", $name, $color);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    $query = "SELECT name, COUNT(*) AS dupes FROM people GROUP BY name ORDER BY dupes DESC LIMIT 20";
    $result = mysqli_query($conn, $query);

    while ($row = $mysqli_fetch_array($result)) {
        array_push($nameArray, $row['name']);
    }

    echo json_encode($nameArray);

    mysqli_close($conn);

?>
  • 写回答

2条回答 默认 最新

  • douci2516 2013-06-13 15:47
    关注

    There's a bug in your PHP code.

    Find this line of code:

    $nameArray[] = "";
    

    Replace to this line of code:

    $nameArray = array();
    

    Update

    Find this line of code:

    $query = "SELECT name, COUNT(*) AS dupes FROM people GROUP BY name ORDER BY dupes DESC LIMIT 20;";
    

    Replace to this line of code

    $query = "SELECT name, COUNT(*) AS dupes FROM people GROUP BY name ORDER BY dupes DESC LIMIT 20";
    

    Note the semicolon inside the string.


    Update Once Again

    Find this line of code:

    while ($row = $mysqli_fetch_array($result)) {
    

    Replace to this line of code

    while ($row = mysqli_fetch_array($result)) {
    

    mysqli_fetch_array is a function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答