沉淀再出发:PHP的中级内容

沉淀再出发:PHP的中级内容

一、前言

    前面我们介绍了PHP的简单的语法知识以及相关的用法,接下来我们将PHP+mysql以及PHP+ajax结合起来进行研究。

二、PHP+mysql

    首先我们看一段代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <body>
 8     <?php
 9         $con=mysqli_connect("127.0.0.1","root","");
10         // Check connection
11         if (mysqli_connect_errno())
12         {
13            echo "Failed to connect to MySQL: " . mysqli_connect_error();
14         }
15 
16         // Create database
17         $sql="CREATE DATABASE zyr_db";
18         if (mysqli_query($con,$sql))
19         {
20             echo "Database zyr_db created successfully";
21             echo '<br>';
22             mysqli_close($con);
23         }
24         else
25         {
26             echo "Error creating database: " . mysqli_error($con);
27             echo '<br>';
28         }
29 
30         $con=mysqli_connect("127.0.0.1","root","","zyr_db");
31         // Check connection
32         if (mysqli_connect_errno())
33         {
34            echo "Failed to connect to MySQL: " . mysqli_connect_error();
35            echo '<br>';
36         }
37 
38         // Create table
39         $sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
40 
41         // Execute query
42         if (mysqli_query($con,$sql))
43         {
44             echo "Table persons created successfully";
45             echo '<br>';
46         }
47         else
48         {
49             echo "Error creating table: " . mysqli_error($con);
50             echo '<br>';
51         }
52 
53         mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age) VALUES ('zyr', 'lsx',24)");
54         mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age) VALUES ('xiaohong', 'xiaoming',30)");    
55         echo "after INSERT...";
56         echo "<br>";
57         findAllPeoples($con);
58 
59         echo "find by firstname ...";
60         echo "<br>";
61         findPeopleById("zyr",$con);
62 
63         mysqli_query($con,"UPDATE Persons SET Age=25 WHERE FirstName='zyr' AND LastName='lsx'");
64         echo "after UPDATE...";
65         echo "<br>";
66         findAllPeoples($con);
67 
68         mysqli_query($con,"DELETE  FROM Persons");
69         echo "after delete...";
70         echo "<br>";
71         findAllPeoples($con);
72         mysqli_close($con);
73 
74         function findPeopleById($name,$con){
75             $result = mysqli_query($con,"SELECT * FROM Persons WHERE FirstName = ". "'" .$name."'");
76 
77             while($row = mysqli_fetch_array($result))
78             {
79                echo $row['FirstName'] . " " . $row['LastName'] ."  ".$row['Age'];
80                echo "<br>";
81             }
82         }
83         function findAllPeoples($con){
84             $result = mysqli_query($con,"SELECT * FROM Persons");
85 
86             while($row = mysqli_fetch_array($result))
87             {
88                echo $row['FirstName'] . " " . $row['LastName'] ."  ".$row['Age'];
89                echo "<br>";
90             }
91         }
92     ?> 
93 
94 </body>
95 </html>

    在我们安装的wamp中,mysql数据库默认的用户名为root,密码为空,因此我们可以连接数据库了,除此之外和其它数据库一样,mysql的数据库操作方法,想必大家都是了如指掌的,并且在PHP之中对于所有的sql操作都做了封装,我们只需要修改或者组合简单的sql语句就能够进行创建、删除数据库、表,以及增删改查表中的内容了,到了这一步,我们可以进行简单的封装使得我们的sql语言更加的精致。

    2.1、创建数据库

 1         $con=mysqli_connect("127.0.0.1","root","");
 2         // Check connection
 3         if (mysqli_connect_errno())
 4         {
 5            echo "Failed to connect to MySQL: " . mysqli_connect_error();
 6         }
 7 
 8         // Create database
 9         $sql="CREATE DATABASE zyr_db";
10         if (mysqli_query($con,$sql))
11         {
12             echo "Database zyr_db created successfully";
13             echo '<br>';
14             mysqli_close($con);
15         }
16         else
17         {
18             echo "Error creating database: " . mysqli_error($con);
19             echo '<br>';
20         }

  2.2、创建表

 1         $con=mysqli_connect("127.0.0.1","root","","zyr_db");
 2         // Check connection
 3         if (mysqli_connect_errno())
 4         {
 5            echo "Failed to connect to MySQL: " . mysqli_connect_error();
 6            echo '<br>';
 7         }
 8 
 9         // Create table
10         $sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
11 
12         // Execute query
13         if (mysqli_query($con,$sql))
14         {
15             echo "Table persons created successfully";
16             echo '<br>';
17         }
18         else
19         {
20             echo "Error creating table: " . mysqli_error($con);
21             echo '<br>';
22         }

    2.3、插入数据

1         mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age) VALUES ('zyr', 'lsx',24)");
2         mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age) VALUES ('xiaohong', 'xiaoming',30)");    
3         echo "after INSERT...";
4         echo "<br>";
5         findAllPeoples($con);

    2.4、查找所有数据

1         function findAllPeoples($con){
2             $result = mysqli_query($con,"SELECT * FROM Persons");
3 
4             while($row = mysqli_fetch_array($result))
5             {
6                echo $row['FirstName'] . " " . $row['LastName'] ."  ".$row['Age'];
7                echo "<br>";
8             }
9         }

    2.5、按条件查找数据

1         echo "find by firstname ...";
2         echo "<br>";
3         findPeopleById("zyr",$con);

     其中findPeopleById("zyr",$con);为:

1         function findPeopleById($name,$con){
2             $result = mysqli_query($con,"SELECT * FROM Persons WHERE FirstName = ". "'" .$name."'");
3 
4             while($row = mysqli_fetch_array($result))
5             {
6                echo $row['FirstName'] . " " . $row['LastName'] ."  ".$row['Age'];
7                echo "<br>";
8             }
9         }

      2.6、更新数据

1         mysqli_query($con,"UPDATE Persons SET Age=25 WHERE FirstName='zyr' AND LastName='lsx'");
2         echo "after UPDATE...";
3         echo "<br>";
4         findAllPeoples($con);

     2.7、删除数据并且关闭数据库

1         mysqli_query($con,"DELETE  FROM Persons");
2         echo "after delete...";
3         echo "<br>";
4         findAllPeoples($con);
5         mysqli_close($con);

     2.8、删除数据库

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <body>
 8        <?php
 9         $con=mysqli_connect("127.0.0.1","root","");
10         // Check connection
11         if (mysqli_connect_errno())
12         {
13            echo "Failed to connect to MySQL: " . mysqli_connect_error();
14         }
15 
16         // Create database
17         $sql="drop DATABASE my_db";
18         if (mysqli_query($con,$sql))
19         {
20             echo "Database zyr_db dropped successfully";
21             mysqli_close($con);
22         }
23         else
24         {
25             echo "Error creating database: " . mysqli_error($con);
26         }
27         ?>
28 </body>
29 </html>

    以上就是数据库相关的操作,使用函数进行相应的封装即可。

   2.9、php和mysql的对应api

当考虑连接到MySQL数据库服务器的时候,有三种主要的API可供选择:
    PHP的MySQL扩展
    PHP的mysqli扩展
    PHP数据对象(PDO)

PHP的MySQL扩展:
      这是设计开发允许PHP应用与MySQL数据库交互的早期扩展。mysql扩展提供了一个面向过程的接口,并且是针对MySQL4.1.3或更早版本设计的。
因此,这个扩展虽然可以与MySQL4.1.3或更新的数据库服务端进行交互,但并不支持后期MySQL服务端提供的一些特性。 PHP的mysqli扩展: mysqli扩展,称之为MySQL增强扩展,可以用于使用 MySQL4.1.3或更新版本中新的高级特性。mysqli扩展在PHP 5及以后版本中包含。
mysqli扩展有一系列的优势,相对于mysql扩展的提升主要有: 面向对象接口 prepared语句支持 多语句执行支持 事务支持 增强的调试能力 嵌入式服务支持 在提供了面向对象接口的同时也提供了一个面向过程的接口。 PDO: PHP数据对象,是PHP应用中的一个数据库抽象层规范。PDO提供了一个统一的API接口可以使得你的PHP应用不去关心具体要连接的数据库服务器系统类型。
也就是说,如果使用PDO的API,可以在任何需要的时候无缝切换数据库服务器,比如从Firebird 到MySQL,仅仅需要修改很少的PHP代码。
其他数据库抽象层的例子包括Java应用中的JDBC以及Perl中的DBI。当然,PDO也有它自己的先进性,比如一个干净的,简单的,可移植的API,
它最主要的缺点是会限制让你不能使用后期MySQL服务端提供所有的数据库高级特性。比如,PDO不允许使用MySQL支持的多语句执行。

     最后我们思考一下,如何在wamp中的mysql之中批量执行sql查询语句呢,这里我们就需要用到mysql的命令行工具了,打开wamp服务器,找到服务器中mysql的按钮,点击之后,选择打开命令行工具,密码默认为空,然后我们创建数据库,并进入数据库之中,之后我们使用source命令来批量执行相应的sql语句。

   更多的关于PHP的mysql接口可以从PHP的官方文档:http://php.net/manual/zh/set.mysqlinfo.php上面获取。

三、PHP和ajax

    在PHP中使用ajax,我们可以非常方便的进行相应的查询和相应,速度非常的快,这对于我们的动态网页来说是非常方便的。

  3.1、数据查询并显示

   首先让我们看一下客户端代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <script>
 7         function showHint(str)
 8         {
 9             if (str.length==0)
10             {
11                 document.getElementById("txtHint").innerHTML="";
12                 return;
13             }
14             if (window.XMLHttpRequest)
15             {// code for IE7+, Firefox, Chrome, Opera, Safari
16                 xmlhttp=new XMLHttpRequest();
17             }
18             else
19             {// code for IE6, IE5
20                 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
21             }
22             xmlhttp.onreadystatechange=function(){
23             if (xmlhttp.readyState==4 && xmlhttp.status==200)
24             {
25                document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
26             }
27             }
28             xmlhttp.open("GET","gethint.php?q="+str,true);
29             xmlhttp.send();
30         }
31     </script>
32 </head>
33 
34 <body>
35 
36     <p><b>在输入框中输入一个姓名:</b></p>
37     <form>
38         姓名: <input type="text" onkeyup="showHint(this.value)">
39     </form>
40     <p>返回值: <span id="txtHint"></span></p>
41 
42 </body>
43 
44 </html>

    然后是PHP服务器的代码(gethint.php):

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <body>
 8         <?php
 9         // 将姓名填充到数组中
10         $a[]="Anna";
11         $a[]="Brittany";
12         $a[]="Cinderella";
13         $a[]="Diana";
14         $a[]="Eva";
15         $a[]="Fiona";
16         $a[]="Gunda";
17         $a[]="Hege";
18         $a[]="Inga";
19         $a[]="Johanna";
20         $a[]="Kitty";
21         $a[]="Linda";
22         $a[]="Nina";
23         $a[]="Ophelia";
24         $a[]="Petunia";
25         $a[]="Amanda";
26         $a[]="Raquel";
27         $a[]="Cindy";
28         $a[]="Doris";
29         $a[]="Eve";
30         $a[]="Evita";
31         $a[]="Sunniva";
32         $a[]="Tove";
33         $a[]="Unni";
34         $a[]="Violet";
35         $a[]="Liza";
36         $a[]="Elizabeth";
37         $a[]="Ellen";
38         $a[]="Wenche";
39         $a[]="Vicky";
40 
41         //从请求URL地址中获取 q 参数
42         $q=$_GET["q"];
43 
44         //查找是否由匹配值, 如果 q>0
45         if (strlen($q) > 0)
46         {
47             $hint="";
48             for($i=0; $i<count($a); $i++)
49             {
50                 if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
51                 {
52                     if ($hint=="")
53                     {
54                         $hint=$a[$i];
55                     }
56                     else
57                     {
58                         $hint=$hint." , ".$a[$i];
59                     }
60                 }
61             }
62         }
63 
64         // 如果没有匹配值设置输出为 "no suggestion"
65         // or to the correct values
66         if ($hint == "")
67         {
68             $response="no suggestion";
69         }
70         else
71         {
72             $response=$hint;
73         }
74 
75         //输出返回值
76         echo $response;
77         ?>
78 </body>
79 </html>

 

  3.2、网上投票

   客户端文件:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <script>
 7     function getVote(int)
 8     {
 9         if (window.XMLHttpRequest)
10         {// code for IE7+, Firefox, Chrome, Opera, Safari
11             xmlhttp=new XMLHttpRequest();
12         }
13         else
14         {// code for IE6, IE5
15             xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
16         }
17         xmlhttp.onreadystatechange=function(){
18             if (xmlhttp.readyState==4 && xmlhttp.status==200)
19             {
20                 document.getElementById("poll").innerHTML=xmlhttp.responseText;
21             }
22         }
23         xmlhttp.open("GET","poll_vote.php?vote="+int,true);
24         xmlhttp.send();
25     }
26     </script>
27 </head>
28 <body>
29     <div id="poll">
30         <h3>Do you like PHP and AJAX so far?</h3>
31         <form>
32             Yes:<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
33             <br>No:
34             <input type="radio" name="vote" value="1" onclick="getVote(this.value)">
35         </form>
36     </div>
37 </body>
38 
39 </html>

   服务器文件(poll_vote.php):

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <body>
 8     <?php
 9         $vote = $_REQUEST['vote'];
10 
11         //get content of textfile
12         $filename = "poll_result.txt";
13         $content = file($filename);
14 
15         //put content in array
16         $array = explode("||", $content[0]);
17         $yes = $array[0];
18         $no = $array[1];
19 
20         if ($vote == 0)
21         {
22         $yes = $yes + 1;
23         }
24         if ($vote == 1)
25         {
26         $no = $no + 1;
27         }
28 
29         //insert votes to txt file
30         $insertvote = $yes."||".$no;
31         $fp = fopen($filename,"w");
32         fputs($fp,$insertvote);
33         fclose($fp);
34     ?>
35 
36     <h2>Result:</h2>
37     <table>
38         <tr>
39             <td>Yes:</td>
40             <td>
41             <img src="poll.gif" width='<?php echo(100*round($yes/($no+$yes),2)); ?>' height='20'>
42             <?php echo(100*round($yes/($no+$yes),2)); ?>%
43             </td>
44         </tr>
45         <tr>
46         <td>No:</td>
47             <td>
48             <img src="poll.gif" width='<?php echo(100*round($no/($no+$yes),2)); ?>' height='20'>
49             <?php echo(100*round($no/($no+$yes),2)); ?>%
50             </td>
51         </tr>
52     </table> 
53 </body>
54 </html>

   文件目录:

四、php+ajax+jQuery

  前端:

  1 <!doctype html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>评论动态加载</title>
  6     <style type="text/css">
  7         .comment{
  8             background: #FFF;
  9             #border-bottom: red solid;
 10             width: 600px;
 11             height: 80px;
 12         }
 13         .comment div img{
 14             width: 80px;
 15             height: 80px;
 16         }
 17         .left{
 18             float: left;
 19             width: 80px;
 20             height: 80px;
 21             background: blue;
 22         }
 23         .right{
 24             float: right;
 25             width: 520px;
 26             height: 80px;
 27         }
 28         #container{
 29             position: relative;
 30             left: 50%;
 31             width: 600px;
 32             margin-left: -300px;
 33         }
 34         #container ul{
 35             padding-left: 0px;
 36             list-style: none;
 37         }
 38         #more{
 39             background: lightGray;
 40             height: 30px;
 41             line-height: 30px;
 42             text-align: center;
 43             cursor: pointer;
 44         }
 45         #clear{
 46             background: red;
 47             height: 30px;
 48             line-height: 30px;
 49             text-align: center;
 50             cursor: pointer;
 51         }
 52     </style>
 53     <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
 54 </head>
 55 <body>
 56 <div style="height:300px;"></div>
 57 <div id="container">
 58 <ul id="contentList">
 59     <li class="comment">
 60         <div class="left"><img src="./g1.jpg"></div>
 61         <div class="right">
 62             <div>一篇工作总结</div>
 63             <div>我是内容</div>
 64         </div>
 65     </li>
 66     <hr>
 67     <li class="comment">
 68         <div class="left"><img src="./g.jpg"></div>
 69         <div class="right">
 70             <div>一篇工作总结</div>
 71             <div>我是内容2</div>
 72         </div>
 73     </li>
 74     <hr>
 75     
 76 </ul>
 77 <div id="more">加载更多...</div>
 78 <div id="clear">清零</div>
 79 <input type="hidden" id="last" value="0">
 80 </div>
 81 
 82 <script type="text/javascript">
 83     $(function(){
 84         $('#more').click(function(){
 85             var last = $('#last').val();
 86             var url = './data.php?last='+last+'&amount=2';
 87             queryComment(url);
 88         });
 89         $('#clear').click(function(){
 90             $('#last').val(0);
 91         });
 92     });
 93 
 94     function queryComment(url){
 95         $.ajax({
 96             type : "get",
 97             async: true,
 98             url : url,
 99             dataType : "json",
100             success : function(data){
101                 if(data == 1){
102                     $('#more').html('没有更多评论!').unbind('click');
103                     return false;
104                 }
105                 $.each(data,function(i,element){
106                     var nickname = element.nickname;
107                     var content = element.content;
108                     var time = element.time;
109                     var imgpath = element.imgpath;
110                     var info = $('<li class="comment"><div class="left"><img src="'+imgpath+'"></div><div class="right"><div>'+nickname+'</div><div></div>'+content+'</div></li><hr>');
111                     $('#contentList').append(info);
112                 });
113                 var now = parseInt($('#last').val()) + 2;
114                 $('#last').val(now);
115             },
116             error:function(){
117                 console.log('fail');
118             }
119         });
120     }
121 </script>
122 </body>
123 </html>

    后端:

 1 <?php
 2 
 3 $con=mysqli_connect("127.0.0.1","root","","mydb");
 4 $last = $_GET['last'];
 5 $amount = $_GET['amount'];
 6 
 7 $query=mysqli_query($con,"select * from comment order by id desc limit $last,$amount");
 8 $flag = false;
 9 while ($row=mysqli_fetch_array($query)) {
10     $flag = true;
11     $sayList[] = array(
12         'id'=>$row['id'],
13         'nickname'=>$row['nickname'],
14         'content'=>$row['content'],
15         'imgpath'=>$row['imgpath'],
16         'time'=>$row['time']
17       );
18 }
19 if($flag){
20     echo json_encode($sayList);
21 }else{
22     echo true;
23 }
24 
25 ?>

  sql语句:

DROP TABLE IF EXISTS `comment`;
CREATE TABLE `comment` (
  `id` int(11) NOT NULL ,
  `nickname` varchar(30)  DEFAULT NULL,
  `content` varchar(30)   DEFAULT NULL,
  `imgpath` varchar(30)   DEFAULT NULL,
  `time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

-- ----------------------------
-- Records of comment
-- ----------------------------
INSERT INTO `comment` VALUES ('1', '1', '23', './g1.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('2', '2', '333', './g2.jpg', '2015-12-22 18:00:21');
INSERT INTO `comment` VALUES ('3', 'zhangsan', 'ceshi3', './g3.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('4', 'zhangsan', 'ceshi4', './g4.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('5', 'zhangsan', 'ceshi5', './g5.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('6', 'zhangsan', 'ceshi6', './g0.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('7', 'zhangsan', 'ceshi7', './g2.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('8', 'zhangsan', 'ceshi8', './g5.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('9', 'zhangsan', 'ceshi9', './g.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('10', 'zhangsan', 'ceshi10', './g2.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('11', 'zhangsan', 'ceshi11', './g3.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('12', 'zhangsan', 'ceshi12', './g4.jpg', '2015-12-21 17:59:54');
INSERT INTO `comment` VALUES ('13', 'zhangsan', 'ceshi13', './g5.jpg', '2015-12-21 17:59:54');
View Code

   运行结果:

五、总结

     我们首先学习了在PHP中如何使用mysql数据库,其次我们学习了PHP中使用ajax的相关技巧,通过上面代码和文档的学习,我们已经有了正式使用PHP的能力了,当然PHP中还有很多其他的功能,在这里我们就不一一列举了。

posted @ 2018-09-18 19:29  精心出精品  阅读(315)  评论(0编辑  收藏  举报