Jump to content

Use of json_encode


sepoto
 Share

Recommended Posts

 <?php$link = mysql_connect('localhost', 'root', '');if (!$link) {	die('Connection error: ' . mysql_error());} $result = mysql_query('use `mydatabase`');if(!result) {die('Query error:' . mysql_error());} $result = mysql_query('select * from locations'); mysql_close($link); echo json_encode($result);?>

I have a sample I prepared that I am working on to get it functional. I see that in the reference for json_encode that the parameter is not allowed to be of the type resource. This leads to the problem of what to do with $result. I suppose I could use a for loop and populate an array and then pass that array to json_encode. I guess the real reason why I post this is to see if someone has some trick to do this that I may not be aware of. Thoughts?

Edited by sepoto
Link to comment
Share on other sites

while($row = mysql_fetch_assoc($table)){ foreach($row as $key => $value) { $arr[$key] = $value; } $main_arr[] = $arr;}$json = json_encode($main_arr); I found this above which is a great example! Is there another way?

Edited by sepoto
Link to comment
Share on other sites

I believe that if you use MySQLi in PHP 5.4, the result is a serializable object (=> should be compatible with json_encode).

Link to comment
Share on other sites

also mysqli has a function which you can use directly to encode http://in3.php.net/manual/en/mysqli-result.fetch-all.php Pleas dont use mysql extension it is obsolete now. use mysqli instead or more better http://php.net/pdo

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...