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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀