Step 1. Create a table in database mysql
with below script.
|
CREATE TABLE `facts` (
`Id` int(11) NOT NULL,
`title` varchar(512) NOT NULL,
`myth`
varchar(512) NOT NULL,
`fact`
varchar(512) NOT NULL
) ENGINE=InnoDB DEFAULT
CHARSET=latin1;
|
Step 2. Create a folder in xampp/htdocs/testRestAPI
Here we need
to create 2 main files
1. Database.php
2. GetAllFacts.php
In database.php
we will write the code for connecting database to php. As shown below.
Database.php
|
<?php
$servername = "localhost";
$username = "manoj";//specify
your username
$password = "root";//specify
your password
try {
$conn = new PDO("mysql:host=$servername;dbname=kamasutra",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
|
In the above
code we are creating connection with php. And this database file is used in
another page there we are getting all the facts and myths about something that
saved in database.
Here is
second file that contains code to get and display data retrieve from database.
GetAllFacts.php
|
<?php
/*
* Following the code will get list of values from code
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
include 'database.php';
// connecting to db
// get a product from products table
$statement = $conn->prepare("select
* from facts");
$statement->execute();
$result =
$statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($result)) {
// check for empty result
$count = sizeof($result);
if ($count > 0) {
$facts = array();
// success
$response["success"] =
1;
// user node
$response["facts"] =
array();
array_push($response["facts"], $result);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] =
0;
$response["message"] =
"No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] =
0;
$response["message"] =
"No product found";
// echo no users JSON
echo json_encode($response);
}
//}
?>
|
The major
difference between API and web application is that Web application will always
return data from file in html, where as in API we have to return data in xml or
JSON.
Nowdays we
are using JSON much more as compare to xml in the above code we are returning
values in JSON format. The output of the above code is .
Output:
|
{
"success":1,
"facts":[
[
{
"Id":"1",
"title":"title1",
"myth":"myth1",
"fact":"fact1"
},
{
"Id":"2",
"title":"title2",
"myth":"myth2",
"fact":"fact2"
}
]
]
}
|
To get full
code and in case of any issue please comment below and subscribe, like our page
for being in touch with us.
Comments
Post a Comment