prismspecs
prismspecs

Reputation: 1489

Trouble getting array back from JSON call to SQL

Just trying to grab everything from a table "guesses" sorted by "cnt" and turn it into a javascript array. Can't get it to give me anything I can work with, though.

PHP file:

<?php 
$dbhost = 'localhost'; 
$dbuser = 'root'; 
$dbpass = 'root'; 
$dbname = 'words'; 
$dbtable = 'guesses'; 

//------ DATABASE CONNECTION --------// 
mysql_connect($dbhost,$dbuser,$dbpass) 
or die ("Unable to connect to database"); 

mysql_select_db($dbname) 
or die ("Unable to select database"); 

$sql = "SELECT * FROM $dbtable ORDER BY cnt ASC";
$result = mysql_query($sql);

while($array = mysql_fetch_assoc($result)) {
    echo json_encode($array);
}

?> 

JavaScript:

    $.getJSON('grab.php', function(response) {
    // response is a JSON object that contains all the info from sql query
    // tried so much stuff here... no avail.
        console.log(response);
})

The console doesn't say anything. "SELECT * FROM guesses ORDER BY cnt ASC" in the phpmyadmin console DOES return the correct entries and order.

EDIT: I've also tried

<?php 
$dbhost = 'localhost'; 
$dbuser = 'root'; 
$dbpass = 'root'; 
$dbname = 'words'; 
$dbtable = 'guesses'; 

//------ DATABASE CONNECTION --------// 
mysql_connect($dbhost,$dbuser,$dbpass) 
or die ("Unable to connect to database"); 

mysql_select_db($dbname) 
or die ("Unable to select database"); 

$sql = "SELECT * FROM $dbtable ORDER BY cnt ASC";
$result = mysql_query($sql);

while($array = mysql_fetch_assoc($result));
echo json_encode($array);

?> 

Which might be syntactically better(???) but it returns "false" to console, and nothing else.

Upvotes: 0

Views: 73

Answers (1)

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11707

You are encoding json at wrong place.

$arr=array();
while($array = mysql_fetch_assoc($result)) {
    array_push($arr,$array);
}
echo json_encode($arr);

Try this

Upvotes: 1

Related Questions