Solved

PHP script to query MYSQL database and return results in JSON format

Posted on 2011-09-29
3
491 Views
Last Modified: 2012-06-22
Hi, I have a PHP/MYSQL calendar script that updates availability for hotels based on their respective room types. Now I need to query that database to return availability based on a given date range and room type, and the result has to be returned in JSON format. Any help will be greatly appreciated.
0
Comment
Question by:Jorge Batres
3 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 36816115
loop over you records/data from your mysql database, don't echo anything else (no html,, head, body tag) in your script
create an array of hash table for each record
and use : http://php.net/manual/en/function.json-encode.php
to transform the array

$days = array();

while ($row = mysql_fetch_assoc($result)) {
    $days[] = array( "field0"=>$row["field0"], "field1"=>$row["field1"], "field2"=>$row["field2"] );
}

header('Content-Type: application/json');
echo json_encode($days);

?>

Open in new window


0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 36891723
No points for this, leakim971 gave the first good answer.

I think you could simplify that code structure and thereby simplify the JSON string.  I might try something like this for the while() loop.
while ($row = mysql_fetch_assoc($result)) {
    $days[] = $row;
}

Open in new window

0
 

Author Comment

by:Jorge Batres
ID: 36893214
Thank you both!
0

Featured Post

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses four methods for overlaying images in a container on a web page
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now