views:

116

answers:

2

How to fetch all result rows in MySQL+PHP?

You know, if I use mysql_fetch_assoc() , it only returns one result row as an associative array. I am using AJAX to fetch the data in a MySQL table.

$result=mysql_query("select * from questions where announcementid='$taskid'")or die(mysql_error());

How to return the value of $result which is an array to the page where an Ajax request was fired?

A: 
    // fetch the results from mysql
    $row = mysql_fetch_assoc( $result ); 

    // output them, encoded as a javascript object
    echo json_encode( $row );

http://php.net/manual/en/function.json-encode.php

You can then access the data as an array in your javascript code on the client side.

rikh
<br /><b>Warning</b>: [json] (json_encode_r) type is unsupported, encoded as null.
Steven
are you sure $result is an array of results and not the resource handle used to access those results?
rikh
$row = mysql_fetch_assoc( $result ); echo json_encode( $row );
Salman A
Updated to include this...
rikh
A: 

hi i think you could add a while function to the php code, and do the same that rikh suggest:

$results = array(); while ( $row = mysql_fetch_assoc( $result )) { $results[] = $row; }

// output them, encoded as a javascript object echo json_encode( $results );

JUGO