Solved

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

Posted on 2011-09-29
3
494 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 109

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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

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

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
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 code hide show and toggles. 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…

821 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