0

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.

9
  • What are your fields in dbtable Commented Nov 28, 2013 at 2:00
  • id, word, cnt are my three fields Commented Nov 28, 2013 at 2:01
  • does alert(response.Id) do anything? Commented Nov 28, 2013 at 2:02
  • can only send one json string to client, you are sending for every pass of loop Commented Nov 28, 2013 at 2:03
  • alert(response.id) returns undefined Commented Nov 28, 2013 at 2:04

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Hmm still returning false :/
when I console.log response, it just says false.
EUREKA! Well done. Now to figure out how to parse this so my front-end brain can make use of it. Ideas? ;-)
$.each over the response
Its better u try it first...:))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.