Create web service with PHP and MySQL
Have you ever heard about the Web Service (web service) ? In this article, I will guide you how to make a web service to serve the requirements of the client easily and simply! First, you need to understand what web service is, right?
WHAT IS WEB SERVICE?
A Web service is a collection that provides methods that allow remote calls via an HTTP URL or another connection method. The result it returns is usually in the form of XML or Json. Because of the remote remote call, it is applied to build distributed systems and applications.
SOME FEATURES OF THE WEB SERVICE
- Can be accessed by any application
- Regardless of the programming language
- Support manipulation between heterogeneous components
- Easy maintenance and low development costs
CREATE WEB SERVICE WITH PHP LANGUAGE AND MYSQL database
In this section, I will guide you to create a simple web service that provides the entire list of students in a returned school in XML or Json format.
Step 1: Create any database then create a data table consisting of fields such as: id, fullName, class. Then insert some test records. You can run the following SQL command to create it immediately.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | CREATE TABLE IF NOT EXISTS `students` ( `id` int (11) NOT NULL AUTO_INCREMENT, `fullName` varchar (50) NOT NULL DEFAULT '', `class` varchar (10) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8 AUTO_INCREMENT = 4; - - Dumping data for table `students` - INSERT INTO `students` (` id`, `fullName`,` class`) VALUES (1, 'Nguyen Van Trong', '9A'), (2, 'Vu Van Khuong', '9B'), (3, 'Dinh Trung Kien', '9C'); |
Step 2: Create a php file located on the web server so that we can call from a specified URL later. You create the webservice.php file with the source code as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | <? php $ db_user = 'root'; // User login MYSQL $ db_pass = 'vertrigo'; // Pass login MySQL $ db_host = 'localhost'; // IP, Domain connection $ db_name = 'test'; // Database name // Create a connection to the database $ conn = mysqli_connect ($ db_host, $ db_user, $ db_pass, $ db_name) or die ('Connection failed'); // Get the type of format you want to get the request $ formatList = array ('json', 'xml'); if (isset ($ _ GET ['format'])) { $ format = $ _GET ['format']; } else { $ format = 'json'; } if (! in_array ($ format, $ formatList)) { $ format = 'json'; } //Query $ query = mysqli_query ($ conn, 'SELECT * FROM students'); // Create the save table $ students = array (); while ($ rs = mysqli_fetch_assoc ($ query)) { $ students [] = $ rs; } // Returns json type if ($ format == 'json') { header ('Content-type: application / json; charset = utf-8'); echo json_encode ($ students); } if ($ format == 'xml') { header ('Content-type: text / xml; charset = utf-8'); echo '<users>'; foreach ($ students as $ student) { echo '<user>'; if (is_array ($ student)) { foreach ($ student as $ key => $ value) { echo '<', $ key, '>', $ value, '</', $ key, '>'; } } echo '</user>'; } echo '</users>'; } mysqli_close ($ conn); ?> <? php $ db_user = 'root'; // User login MYSQL $ db_pass = 'vertrigo'; // Pass login MySQL $ db_host = 'localhost'; // IP, Domain connection $ db_name = 'test'; // Database name // Create a connection to the database $ conn = mysqli_connect ($ db_host, $ db_user, $ db_pass, $ db_name) or die ('Connection failed'); // Get the type of format you want to get the request $ formatList = array ('json', 'xml'); if (isset ($ _ GET ['format'])) { $ format = $ _GET ['format']; } else { $ format = 'json'; } if (! in_array ($ format, $ formatList)) { $ format = 'json'; } //Query $ query = mysqli_query ($ conn, 'SELECT * FROM students'); // Create the save table $ students = array (); while ($ rs = mysqli_fetch_assoc ($ query)) { $ students [] = $ rs; } // Returns json type if ($ format == 'json') { header ('Content-type: application / json; charset = utf-8'); echo json_encode ($ students); } if ($ format == 'xml') { header ('Content-type: text / xml; charset = utf-8'); echo '<users>'; foreach ($ students as $ student) { echo '<user>'; if (is_array ($ student)) { foreach ($ student as $ key => $ value) { echo '<', $ key, '>', $ value, '</', $ key, '>'; } } echo '</user>'; } echo '</users>'; } mysqli_close ($ conn); ?> |
The above code takes the parameters passed on the URL as a format to determine the type of data to return:
- URL gets information in the form of Json:
1 | http: //localhost/test/webservice.php? format = json |
- URL retrieves information in XML format:
1 | http: //localhost/test/webservice.php? format = xml |
With the above parameters, the web service will execute to retrieve all student data and return the data. For example, taking XML will have the following data set:
1 | <users><user><id>1</id> <fullName> Nguyen Van Trong </fullName> <class> 9A </class> </user> <user> <id> 2 </id> <fullName> Vu Van Khuong </fullName> <class> 9B </class> </user> <user> <id> 3 </id> <fullName> Dinh Trung Kien </fullName> <class> 9C </class> </ user> </users> |
Step 3: Create the client.php file with the source code content as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <? php // Data returned in json format $ jsonData = file_get_contents ("http: //localhost/test/webservice.php? format = json"); $ jsonArray = json_decode ($ jsonData, true); var_dump ($ jsonArray); <? php // Data returned in json format $ jsonData = file_get_contents ("http: //localhost/test/webservice.php? format = json"); $ jsonArray = json_decode ($ jsonData, true); var_dump ($ jsonArray); |
SUMMARY
From the above example, you just need to understand simply that webservice is only a service where it receives requests via URL and parameters, then it will handle returning data in xml format or json that you desire at the request of the service user.
Building webservice for the application is very useful because the json or xml format is a data format that can be used on many mobile platforms such as android, ios, … or websites like PHP, JSP, ASP.net, C # , ….
ITZone via kienthucweb.net