Professional Documents
Culture Documents
PHP v MySQL
Kungfu PHP 14 Thng Hai, 2015 Hng dn to web service vi PHP v MySQL2017-05-
06T07:55:23+00:00Tng hp PHP 8 Comments
1. Web services l g ?
2. c im ca web service
Khng ph thuc vo ngn ng lp trnh
C th c truy cp t bt c ng dng no
D bo tr
MySQL
Bc 2 : To mt th mc tn l webservice, t trong th mc gc ca
website. Tip n trong th mc webservice, to 1 file t tn l
connection.php. File ny c trch nhim to kt ni n c s d liu.
PHP
<?php
1
$server_username = "root"; // in username ng nhp mysql
2
$server_password = ""; // in password ng nhp mysql
3
$server_host = "localhost";// in tn host
4
$database = 'kungfuphp'; // tn database
5
6
// to bin kt ni ti database
7
$conn = mysqli_connect($server_host,$server_username,$server_password,$database) or die("khng th
8
kt ni ti database");
PHP
1 <?php
2 if(isset($_GET["getUser"])){
3 // kim tra nh dng d liu tr ra l json hay xml
4 $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml';
5
6
7 //to mng users lu thng tin ton b user trong db
8 $users = array();
9
10 //gi file kt ni db
11 require_once("connection.php");
12 //truy vn ly ton b thng tin trong bng users
13 $sql = "select * from users";
14 $query = mysqli_query($conn,$sql);
15 while ($user = mysqli_fetch_assoc($query) {
16 $users[] = array('user' => $user);
17 }
18 // tr ra d liu di dng json
19 if ($format == 'json') {
20 header('Content-type: application/json');
21 echo json_encode(array('users'=>$users));
22 }else{
23 // tr ra d liu di dng xml
24 header('Content-type: text/xml');
25 echo '<users>';
26 foreach($users as $index => $user) {
27 if(is_array($user)) {
28 foreach($user as $key => $value) {
29 echo '<',$key,'>';
30 if(is_array($value)) {
31 foreach($value as $tag => $val) {
32 echo '<',$tag,'>',htmlentities($val),'</',
33 $tag,'>';
34 }
35 }
36 echo '</',$key,'>';
37 }
38 }
39 }
40 echo '</users>';
41 }
mysqli_close();
}else{
42
echo "Khng c d liu tr v";
43
}
PHP
1 http://localhost/webservice?getUser&format=json
PHP
1 http://localhost/webservice?getUser&format=xml
XHTML
4. Tng kt