This article mainly introduces the PHP simple implementation query database to return JSON data, and attached 2 sample code, very simple and practical, the need for small partners to refer to.
Example code one:
Sets the return JSON format Data header (' Content-type:application/json;charset=utf8 ');//Connect Database $link = mysql_connect ("localhost", " Root "," root ") or Die (" unable-to-connect to the mysql! "); mysql_query ("SET NAMES ' UTF8 '"); mysql_select_db ("Jilinwula", $link) or die ("Unable to connect to the mysql!"); /Get paging parameter $page = 0; $pageSize = 3;if (!is_null ($_get["page")) {$page = $_get["page"];} if (!is_null ($_get["PageSize")) {$pageSize = $_get["PageSize"];} Query the data into the array $result = mysql_query ("Select Username,password from UserInfo limit". $page. ", ". $pageSize. ""); $results = Array (), while ($row = Mysql_fetch_assoc ($result)) {$results [] = $row;} Turn the array into JSON format echo json_encode ($results);//close Connection mysql_free_result ($result); Mysql_close ($link);
Example code two:
<?php//need to execute SQL statement//single $sql= "Select Id,name from Tbl_user where id=1";//Multiple data//$sql = "Select Id,name from Tbl_user";// Call the conn.php file for database operation require (' conn.php '); Prompt Operation success Information, note: $result exists in the conn.php file, is called out if ($result) {//$array =mysql_fetch_array ($result, MYSQL_ASSOC); /* Data set $users =array (); $i = 0; while ($row =mysql_fetch_array ($result, Mysql_assoc)) { echo $row [' id ']. ' -----------'. $row [' name ']. ' </br> '; $users [$i]= $row; $i + +; } Echo Json_encode (Array (' dataList ' = $users)); */* Single data */$row =mysql_fetch_row ($result, MYSQL_ASSOC); echo json_encode (Array (' jsonobj ' = $row));} Mysql_free_result ($result);//release result mysql_close ();//close Connection?>
Summary : The above is the entire content of this article, I hope to be able to help you learn.
Related recommendations:
PHP implementation of Web Caching tool class code and how to use
PHP controls all background function calls based on AJAX implementation
File and form operation and database operation involved in uploading PHP files