In my previous post I was talking about how to install WAMP and create your DataBase. Here we will create a RESTfull web service with PHP.
We created our User table with some users in it. Now we want to get this user list in a “universal” way. It means any kind of code could potentially access our web service via JSON messages and the standard HTTP protocol.
Create the PHP REST service
When you installed WAMP, it created a WWW folder in the WAMP folder path (for example: C:\wamp\www). Create a new file called DbUsersApi.php for example and another one called DbSettings.php and open them with Notepad, Notepad++, Sublime Text or another text editor.
Paste this PHP code in DbSettings.php:
<?php
//Allows CORS (cross domain requests)
header("Access-Control-Allow-Origin: *");
//Set all the parameters for MySql
$user_name = "YOUR SQL USERNAME";
$password = "YOUR SQL PASSWORD";
$database = "YOUR SQL DATABASE NAME";
$server = "127.0.0.1";
//Connect to MySql
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) { /*print "<br/>Database Found: " . $database;*/ }
else { print "<br/>Database NOT Found"; }
?>Save it and open DbUsersApi.php and past this:
<?php include "DbSettings.php"; ?>
<?php
function get_user_list()
{
//Query in the User SQL Table
$SQL = "SELECT * FROM User";
$result = mysql_query($SQL);
$user_list = array();
//Display the SQL result as an Array of Users
while ( $db_field = mysql_fetch_assoc($result) ) {
$user_list[] = array(
"userid" => $db_field['userid'],
"firstname" => $db_field['firstname'],
"lastname" => $db_field['lastname']);
}
return $user_list;
}
//List of all the possible method calls from the URL
$possible_url = array( "get_user_list");
//By default the resulting value will be an error, until it change by the correct one
$value = "An error has occurred (is this action included in possible URLs ?)";
//Check if the call is correct and if the parameter of the call is included in the possible URL's
if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))
{
switch ($_GET["action"])
{
case "get_user_list":
$value = get_user_list();
exit(json_encode(array("user_list" => $value)));
break;
}
}
//return JSON array
exit(json_encode($value));
?>Now if you go in a web browser and you put this address:
http://localhost/DbUsersApi.php?action=get_user_list
Then you should see the JSON result of your users in the database.
See my post about how to consume this web service with Javascript.




No Comments Yet