沉澱再出發:PHP的中級內容

沉澱再出發:PHP的中級內容

1、前言

    前面咱們介紹了PHP的簡單的語法知識以及相關的用法,接下來咱們將PHP+mysql以及PHP+ajax結合起來進行研究。javascript

2、PHP+mysql

    首先咱們看一段代碼: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         $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語言更加的精緻。css

    2.一、建立數據庫

 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.二、建立表

 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.三、插入數據

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.四、查找全部數據

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.五、按條件查找數據

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

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

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.六、更新數據

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.七、刪除數據而且關閉數據庫

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

     2.八、刪除數據庫

 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.九、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語句。java

   更多的關於PHP的mysql接口能夠從PHP的官方文檔:http://php.net/manual/zh/set.mysqlinfo.php上面獲取。mysql

3、PHP和ajax

    在PHP中使用ajax,咱們能夠很是方便的進行相應的查詢和相應,速度很是的快,這對於咱們的動態網頁來講是很是方便的。jquery

  3.一、數據查詢並顯示

   首先讓咱們看一下客戶端代碼:ajax

 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):sql

 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.二、網上投票

   客戶端文件:

 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>

   文件目錄:

4、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

   運行結果:

5、總結

     咱們首先學習了在PHP中如何使用mysql數據庫,其次咱們學習了PHP中使用ajax的相關技巧,經過上面代碼和文檔的學習,咱們已經有了正式使用PHP的能力了,固然PHP中還有不少其餘的功能,在這裏咱們就不一一列舉了。

相關文章
相關標籤/搜索