Question

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

?>
Was it helpful?

Solution

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.

OTHER TIPS

you have error here

$nameArray[] = "";

and you need to replace this with

$nameArray[] = array();

Now the reason is this that in your code you are initializing an array with no values and not even any index so this will generate error. but if you replace it with array() it will initialize an array. When you will push values array_push($nameArray, $row['name']); into this it will push value in array on index 0 and then on 1 and so on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top