PHP 开发基础知识笔记
PHP 基本語(yǔ)法
普通變量: 普通變量的定義語(yǔ)法,以及通過(guò)各種方式判斷字符串是否為空.
<?php$var = ""; // 定義字符串define("CON_INT",100); // 定義常量if(empty($var))echo "字符串為空 <br>";if(isset($var))echo "字符串為空 <br>";if(!is_null($var))echo "字符串為空 <br>";if(is_string($var))echo "字符串變量 <br>";if(defined("CON_INT"))echo "屬于常量 <br>";echo "當(dāng)前系統(tǒng)是: " . PHP_OS . "<br>";echo "當(dāng)前PHP版本: " . PHP_VERSION . "<br>";echo "當(dāng)前的行號(hào)是: " . __LINE__ . "<br>";echo "當(dāng)前的PHP文件名: " . __FILE__ . "<br>" ?>PHP中運(yùn)算符:
<?php$x = 10%3;$year = 2018;var_dump($x);try{if(($year%4==0 && $year%100!=0)||($year%400==0))echo "%year 是閏年 <br>";elseecho "%year 是平年 <br>";$error = "產(chǎn)生異常.";// throw new Exception($error);}catch(Exception $e){echo "異常類型: " . $e->getMessage() . "<br>";} ?>where 循環(huán)與判斷:
<html><body><table align="center" border="1" width=600><caption><h2>where 循環(huán)</h2></caption><?php$out=0;while ($out < 5){if($out%2===0)$bgcolor = "#fffffff";else$bgcolor = "#ddddddd";echo "<tr bgcolor=" . $bgcolor . ">";$in = 0;while($in < 10){echo "<td>" . ($out*10+$in). "</td>";$in++;}echo "</tr>";$out++;}?></body> </html>for循環(huán):
<html><body><?phpfor($x=1; $x<=9; $x++){for($y=1; $y<=$x; $y++){echo "$y * $x = ". $y*$x . " ";}echo "<br>";}?><?phpfor($x=9; $x>=1; $x--){for($y=$x; $y>=1; $y--){echo "$y * $x = ". $y*$x . " ";}echo "<br>";}?></body> </html>函數(shù)參數(shù)傳遞:
<?phpfunction CreateTable($table_name,$rows,$cols){echo "<table align='center' border='1' width=600>";echo "<caption><h2> $table_name </h2></caption>";for($out=0; $out<$rows; $out++){echo "<tr>";for($in=0; $in<$cols; $in++){echo "<td>" . ($out*$cols+$in) . "</td>";}echo "</tr>";}}CreateTable("財(cái)務(wù)部",5,5);CreateTable("銷售部",3,3); ?>可變長(zhǎng)參數(shù)傳遞:
<?php// 普通固定參數(shù)傳遞function Person($name="lyshark",$age=24){echo "姓名: {$name},年齡: {$age} <br>";}Person("admin",33);// 可變長(zhǎng)參數(shù)傳遞function more_args(){$args = func_get_args();for($x=0; $x<count($args); $x++){echo "第 {$x} 個(gè)參數(shù)是 -> {$args[$x]} <br>";}}more_args("admin","guest","lyshark");// 可變長(zhǎng)變量函數(shù)function func_one($x,$y){return $x+$y;}function func_two($x,$y){return $x*$y;}$point = "func_one";echo "call func_one: " . $point(2,3) . "<br>";$point = "func_two";echo "call func_one: " . $point(2,3) . "<br>"; ?>設(shè)置Cookie登錄: 基于Cookie設(shè)置實(shí)現(xiàn)的用戶登錄模塊,清空與設(shè)置Cookie選項(xiàng).
<?phpfunction ClearCookie(){setCookie('username','',time()-3600);setCookie('isLogin','',time()-3600);}// 檢測(cè)是否登陸路,如果登錄則提示你好if($_COOKIE['isLogin']){echo "您好: " . $_COOKIE['username'] . "<br>";echo "<a href='index.php?action=logout'>退出</a>";}// 判斷用戶是否執(zhí)行登錄if($_GET['action']=='login'){ClearCookie();if($_POST['username']=='admin' && $_POST['password']='123123'){setCookie('username',$_POST['username'],time()+60*60*24*7);setCookie('isLogin','1',time()+60*60*24*7);header("Location:index.php");}else{echo "密碼錯(cuò)誤";}}else if($_GET['action']=="logout"){ClearCookie();header("Location:index.php");} ?><form action="index.php?action=login" method="post">用戶: <input type="text" name="username" size=25><br>密碼: <input type="password" name="password" size=25><input type="submit" value="登錄"> </form>PHP 數(shù)組操作
數(shù)組的賦值: PHP中的數(shù)組既可以做數(shù)組,也可以做鍵值對(duì)字典,且不存在限制,非常靈活.
<?php// 定義純數(shù)組格式$array_one[0] = 100;$array_one[1] = 200;$array_one[2] = "lyshark";$array_one[3] = [1,2,3,4,5,6];echo $array_one[0] . $array_one[2] . "<br>";echo "數(shù)組中的數(shù)組: " . $array_one[3][1] . "<br>";// 定義字典格式的數(shù)組$array_two['ID'] = 1001;$array_two['name'] = "lyshark";$array_two['age'] = 25;echo "姓名: " . $array_two['name'] . "<br>"; ?>數(shù)組的定義與遍歷: 分別定義一維數(shù)組與二維數(shù)組,并通過(guò)兩種方式分別遍歷數(shù)組元素.
<?php// 定義一維數(shù)組$var = array("first"=>1,"second"=>2,"third"=>3,"montd"=>4);foreach ($var as $key => $value){echo "鍵 => {$key} --> 值 => {$value} <br>";}// 定義二維數(shù)組$var_two = array("書籍" => array("文學(xué)","歷史","地理"),"水果" => array(1=>"蘋果",2=>"橙子",3=>"水蜜桃"));foreach($var_two as $key => $value){echo "鍵=" . $key . " ";foreach($var_two[$key] as $index => $value){echo " 索引: " . $index . " --> 值: " . $value;}echo "<br>";}// 二維數(shù)組其他遍歷方法$array_two = array(array('北京','上海','深圳','廣州'),array('黑龍江','吉林','遼寧','江蘇'));for($x=0; $x< count($array_two); $x++){for($y=0; $y<count($array_two[$x]); $y++){echo "輸出數(shù)組: " . $array_two[$x][$y] . "<br>";}} ?>數(shù)組元素統(tǒng)計(jì): 統(tǒng)計(jì)出數(shù)組中指定元素的個(gè)數(shù),或者統(tǒng)計(jì)每個(gè)元素出現(xiàn)的次數(shù).
<?php// 一維數(shù)組統(tǒng)計(jì)$lamp = array("Linux","Apache","MySQL","PHP");echo "lamp 元素個(gè)數(shù): " . count($lamp) . "<br>";// 二維數(shù)組統(tǒng)計(jì)$web = array('lamp' => array("Linux","Apache","MySQL","PHP"),'j2ee' => array("Unix","Tomcat","Oracle"));echo "二維中一維個(gè)數(shù): " . count($web) . "<br>";echo "整個(gè)數(shù)組的大小: " . count($web,1) . "<br>";// 統(tǒng)計(jì)元素出現(xiàn)次數(shù),返回?cái)?shù)組$array = array("php","asp","jsp","php","python","node.js");$new_array = array_count_values($array);foreach($new_array as $key => $value){echo "數(shù)組元素 => {$key} ---> 出現(xiàn)頻率 => {$value} <br>";} ?>二維數(shù)組遍歷回顯: 通過(guò)傳統(tǒng)的循環(huán)結(jié)構(gòu)遍歷特定數(shù)組中的元素,并用表格展示出來(lái).
<?php$data = array(array(1,'admin','北京',"admin@blib.cn"),array(2,'guest','天津',"guest@blib.cn"),array(3,'lyshark','洛杉磯',"lyshark@blib.cn"));echo "<table border='1' width='600' align='center'>";echo "<caption><h1>輸出列表</h1></caption>";echo "<tr bgcolor='#ddddddd'>";echo "<th>編號(hào)</th><th>姓名</th><th>住址</th><th>郵箱</th>";echo "</tr>";for($row=0; $row < count($data); $row++){echo "<tr>";for($clo=0; $clo<count($data[$row]); $clo++){echo "<td>" . $data[$row][$clo] . "</td>";}echo "</tr>";}echo "</table>"; ?>三維數(shù)組遍歷回顯: 由于FOR語(yǔ)句遍歷數(shù)組的局限性,所以PHP中提供了更加強(qiáng)大的ForEach結(jié)構(gòu).
<?php$data = array("市場(chǎng)部" => array(array(1,"張某","經(jīng)理",5000),array(2,"劉某","員工",3000)),"銷售部" => array(array(1,"李某","職員",2000),array(2,"孫某","經(jīng)理",6000)),"財(cái)務(wù)部" => array(array(1,"吳某","經(jīng)理",8000)));foreach($data as $sector => $table){echo "<table border='1' width='600' align='center'>";echo "<caption><h1>" . $sector . "</h1></caption>";echo "<tr bgcolor='#ddddddd'>";echo "<th>編號(hào)</th><th>姓名</th><th>職務(wù)</th><th>薪資</th>";echo "</tr>";foreach($table as $row){echo "<tr>";foreach($row as $col){echo "<td>" . $col . "</td>";}echo "</tr>";}echo "</table><br>";} ?>指針操作數(shù)組: 數(shù)組內(nèi)部指針式數(shù)組內(nèi)部的組織機(jī)制,指向一個(gè)數(shù)組中的某個(gè)元素.
<?php$info = array('admin','guest','lyshark');// 將數(shù)組中所有的的元素轉(zhuǎn)換為變量list($x,$y,$z) = $info;echo "變量: " . $x . $y . $z . "<br>";// 將數(shù)組中指定元素轉(zhuǎn)換為變量list(,,$z)= $info;echo "變量: " . $z . "<br>";// 數(shù)組指針操作reset($info);echo "元素索引: " . key($info) . "元素值: " . current($info) . "<br>";next($info);echo "元素索引: " . key($info) . "元素值: " . current($info) . "<br>";prev($info);echo "元素索引: " . key($info) . "元素值: " . current($info) . "<br>";end($info);echo "元素索引: " . key($info) . "元素值: " . current($info) . "<br>";// 通過(guò)指針循環(huán)遍歷for(reset($info); current($info);next($info)){echo "數(shù)據(jù): " . current($info) . "<br>";} ?>數(shù)組鍵值對(duì)操作: 數(shù)組中的每個(gè)元素都是由鍵值對(duì)組成的,通過(guò)元素的鍵訪問(wèn)對(duì)應(yīng)的值.
<?php$info = array("ID" => 1001,"Name" => "admin","Age" => 24 );$var1 = array("a"=>"python","b"=>"php","c"=>"C/C++","d"=>"java");$var2 = array("1"=>"a","2"=>"b","3"=>"c","4"=>"d");// 獲取所有的鍵值print_r(array_keys($info));print_r(array_values($info));// 獲取特定的鍵print_r(array_keys($info,"admin"));// 值作為新數(shù)組的鍵$new = array_combine($var1, $var2);print_r($new); echo"<br>";// extrace()將數(shù)組轉(zhuǎn)換成標(biāo)量變量extract($var1);echo $a."<br>";echo $b."<br>"; ?>判斷鍵值是否存在: 檢查特定數(shù)組中是否存在某個(gè)值,即在數(shù)組中搜索給定的值.
<?php// 函數(shù)的簡(jiǎn)單用法$info = array("Mac","Windows NT","AIX","Linux");if(in_array("Mac",$info))echo "存在 <br>";// 嚴(yán)格模式,必須類型一致,否則失敗$info = array('10.24',12,45,1,2);if(in_array(10.24,$info,true))echo "存在 <br>";// 查詢數(shù)組中的數(shù)組$info = array(array(1,2),array(3,4));if(in_array(array(3,4),$info))echo "存在 <br>";// search 同樣可以實(shí)現(xiàn)檢索$info = array("ID" => 1001,"Name" => "admin","Age" => 24 );if(array_search("admin",$info))echo "存在 <br>";// 檢查下標(biāo)元素是否在數(shù)組中if(array_key_exists('ID',$info))echo "存在 <br>";// 使用isset同理if(isset($info['ID']))echo "存在 <br>"; ?>數(shù)組交換/統(tǒng)計(jì)/去重: 實(shí)現(xiàn)數(shù)組的交換,統(tǒng)計(jì),與去重等操作.
<?php$info = array("OS" => "Linux","WebServer" => "Nginx", "DataBase" => "MySQL");// 交換數(shù)組中的鍵值$new_info = array_flip($info);print_r($info); echo "<br>";print_r($new_info); echo "<br>";// 數(shù)組元素反轉(zhuǎn)$new_info = array_reverse($info);print_r($info); echo "<br>";print_r($new_info); echo "<br>";// 統(tǒng)計(jì)元素個(gè)數(shù)$var_count = count($info);echo "元素個(gè)數(shù): " . $var_count . "<br>";// 統(tǒng)計(jì)數(shù)組中所有元素出現(xiàn)次數(shù)$array = array(1,2,3,3,2,4,5,6,6,7,7,7,6,8,7,4,3);$array_count = array_count_values($array);print_r($array_count); echo "<br>";// 數(shù)組元素去重操作$array = array("1" => "PHP","2" => "MySQL","3" => "PHP");print_r(array_unique($array)); ?>數(shù)組回調(diào)與過(guò)濾: PHP提供了回調(diào)函數(shù),可以實(shí)現(xiàn)對(duì)數(shù)組中元素的過(guò)濾功能,例如將每個(gè)元素遞增10等.
<?php// array_filter 定義第一個(gè)回調(diào)函數(shù)function EvenNumber($var){if($var %2 ==0) return true;}$info = array(1,2,3,4,5,6,7,8,9,10);print_r(array_filter($info,"EvenNumber"));echo "<br>";// array_walk 第二種回調(diào)函數(shù)的過(guò)濾寫法function PrintFunction($value,$key){$value = $value + 10;echo "KEY= " . $key . " VALUE= " . $value . "<br>";}$info = array("UID" => 1001,"GID" => 0, "age"=> 25);array_walk($info,"PrintFunction");// array_map 第三種回調(diào)函數(shù)過(guò)濾寫法(可替換指定數(shù)組元素)function ReplaceMap($var1){if($var1 === "MySQL")return "Oracle";return $var1;}$info = array("Linux","Windows","Apache","MySQL","PHP");print_r(array_map("ReplaceMap",$info));echo "<br>";// array_map 傳遞多個(gè)參數(shù)實(shí)現(xiàn)回調(diào) (可用于對(duì)比多個(gè)數(shù)組的異同點(diǎn))function Contrast($var1,$var2){if($var1 == $var2)return "True";return "False";}$Array_A = array("Linux","PHP","MySQL");$Array_B = array("Linux","MySQL","MySQL");print_r(array_map("Contrast",$Array_A,$Array_B)); ?>基本的數(shù)組排序: 在PHP中提供了多種排序函數(shù),相比于C來(lái)說(shuō)更加的簡(jiǎn)單實(shí)用.
<?php// 對(duì)數(shù)組進(jìn)行正反向排序$info = array(5,6,8,2,7,8,9,0,2,1,3,4,5);if(sort($info))echo "sort 正向排序:"; print_r($info);echo "<br>";if(rsort($info))echo "sort 反向排序:"; print_r($info);echo "<br>";// 根據(jù)key=>鍵名稱來(lái)實(shí)現(xiàn)數(shù)組排序$info = array(5 => "five",8 => "eight",1 => "one");if(ksort($info))echo "ksort 正向排序:"; print_r($info);echo "<br>";if(krsort($info))echo "ksort 反向排序:"; print_r($info);echo "<br>";// 根據(jù)value=>值來(lái)實(shí)現(xiàn)數(shù)組排序$info = array(5 => "five",8 => "eight",1 => "one");if(asort($info))echo "asort 正向排序:"; print_r($info);echo "<br>";if(arsort($info))echo "asort 反向排序:"; print_r($info);echo "<br>";// 根據(jù)自然排序法對(duì)數(shù)組排序$info = array("file1","file11","File2","FILE12","file");if(natsort($info))echo "natsort 大寫排在前面:"; print_r($info);echo "<br>";if(natcasesort($info))echo "natcasesort 忽略大小寫自然排序:"; print_r($info);echo "<br>"; ?>自定義/多維數(shù)組排序: 除了使用上面提供的排序方法以外,我們還可以自定義排序規(guī)則.
<?php// 回調(diào)函數(shù)實(shí)現(xiàn)自定義排序$info = array("Linux","Apache","MySQL","PHP");function SortByLen($var1,$var2){// 如果兩個(gè)字符串長(zhǎng)度一致則保留if(strlen($var1) === strlen($var2))return 0;elsereturn (strlen($var1)>strlen($var2)?1:-1);}if(usort($info,"SortByLen"))echo "自定義排序:"; print_r($info);echo "<br>";// 多維數(shù)組的排序方法$info = array(array("id" => 1,"soft" => "Linux","rating" => 8),array("id" => 2,"soft" => "Apache","rating" => 1),array("id" => 3,"soft" => "Nginx","rating" => 5));foreach($info as $key => $value){// 將$info中每個(gè)元素中鍵為soft的值形成新數(shù)組$soft$soft[$key] = $value["soft"];$rating[$key] = $value['rating'];}array_multisort($rating,$soft,$info); // 開(kāi)始排序echo "多維數(shù)組排序: "; print_r($info); echo "<br>"; ?>拆分/合并/分解數(shù)組: 數(shù)組常用的處理函數(shù),包括對(duì)數(shù)組進(jìn)行拆分,合并,結(jié)合,等常用操作.
<?php// array_slice(數(shù)組,開(kāi)始下標(biāo),取出個(gè)數(shù)) 在數(shù)組中根據(jù)條件取值并返回.$info = array("Linux","PHP","Apache","MySQL","Nginx","Zabbix");print_r(array_slice($info,1,2));echo "<br>";// array_splice(數(shù)組,開(kāi)始下標(biāo),替換次數(shù),替換為) 替換指定數(shù)組中的指定元素$info = array("Linux","PHP","Apache","MySQL","Nginx","Zabbix");array_splice($info,1,1,"AAAA");echo "將下標(biāo)1的位置替換為AAAA "; print_r($info); echo "<br>";array_splice($info,2);echo "從第2個(gè)元素向后的都刪除掉 "; print_r($info); echo "<br>";// array_combine() 將兩個(gè)數(shù)組合并為新數(shù)組 (兩個(gè)數(shù)組必須相等)// 其中第一個(gè)數(shù)組為KEY 第二個(gè)數(shù)組為Value$key = array("1","2","3");$value = array("Apache","Nginx","Cpp");$new_array = array_combine($key,$value);echo "合并后: "; print_r($new_array); echo "<br>";// array_merge() 將兩個(gè)數(shù)組合并為新數(shù)組 (合并時(shí)自動(dòng)去重)$varA = array("a" => "Linux","b" => "MySQL");$varB = array("c" => "Python","a" => "PHP");echo "合并后: "; print_r(array_merge($varA,$varB)); echo "<br>";// array_ntersect()/array_diff() 計(jì)算兩個(gè)數(shù)組的交集/差集$varA = array(1,2,3,4,5);$varB = array(3,4,5,6,7);echo "交集: "; print_r(array_intersect($varA,$varB));echo "<br>";echo "差集: "; print_r(array_diff($varA,$varB));echo "<br>"; ?>數(shù)組模擬實(shí)現(xiàn)棧/隊(duì)列: 數(shù)組同樣可以實(shí)現(xiàn)棧與隊(duì)列的基本操作,如下所示.
<?php// 實(shí)現(xiàn)數(shù)組棧$stack = [];array_push($stack,1);array_push($stack,2);array_pop($stack);echo "簡(jiǎn)易版: "; print_r($stack);echo "<br>";// key-value類型的棧$kv_stack = array(1 =>"Linux");array_push($kv_stack,2,"Apache");echo "key-value版棧: "; print_r($kv_stack);echo "<br>";// 實(shí)現(xiàn)隊(duì)列$kv_loop = array(1 =>"Linux");array_unshift($kv_loop, 2, "Apache");array_shift($kv_loop);echo "key-value 版隊(duì)列: "; print_r($kv_loop);echo "<br>"; ?>數(shù)組的打亂/互轉(zhuǎn): 實(shí)現(xiàn)對(duì)數(shù)組的打亂,或?qū)?shù)組與字符串實(shí)現(xiàn)互相轉(zhuǎn)換.
<?php// $var = array(1,2,3,4,5,6,7,8,9,10);$var = range(0,10);echo "當(dāng)前數(shù)組: "; print_r($var); echo "<br>";echo "隨機(jī)取出一個(gè)元素: " . array_rand($var,1) . "<br>";echo "隨機(jī)打亂數(shù)組: " . shuffle($var) . "<br>";echo "數(shù)組求和: " . array_sum($var) . "<br>";array_unshift($var, "perl"); # 在數(shù)組頭部添加元素print_r($var);echo "<br>";array_push($var, "golang"); # 在數(shù)組尾部添加元素print_r($var);echo "<br>";array_shift($var); # 刪除數(shù)組第一個(gè)元素print_r($var);echo "<br>";array_pop($var); # 刪除數(shù)組最后一個(gè)元素print_r($var);echo "<br>";// 將數(shù)組轉(zhuǎn)為字符串/數(shù)組到字符串,互轉(zhuǎn).$var = array("python","php","C","java");$var = implode(",", $var); # 數(shù)組轉(zhuǎn)換為字符串echo "字符串: "; print_r($var); echo "<br>";$var = explode(",", $var); # 字符串轉(zhuǎn)數(shù)組echo "數(shù)組: "; print_r($var); echo "<br>"; ?>PHP 字符操作
字符串輸出: 在PHP中,字符串的輸出可以使用多種函數(shù)來(lái)實(shí)現(xiàn),最基本的輸出方式如下.
<?php// printf 普通的輸出函數(shù)$string = "hello lyshark";$number = 1024;printf("%s page number = > %u <br>",$string,$number);// echo 的使用方法$name = "lyshark";$age = 25;echo "姓名: {$name} 年齡: {$age} <br>";// sprintf 將內(nèi)容輸出到緩沖區(qū)中$text = sprintf("float = > %0.2f",$number);echo "打印輸出內(nèi)容: " . $text . "<br>";// 第三種輸出方式print_r("姓名: " . $name . "年齡:" . $age . "<br>");var_dump($name); ?>字符串處理函數(shù): 針對(duì)字符串的大小寫轉(zhuǎn)換,去重左右去空格,左右補(bǔ)齊,等基本操作.
<?php$string = "@@ hello lyshark @@";// 字符串左右去除printf("字符串長(zhǎng)度: %d <br>",strlen($string));printf("字符串截取: %s <br>",substr($string,2,4));printf("去除左側(cè)空字符: %s <br>",ltrim($string));printf("去除左側(cè)@字符: %s <br>",ltrim($string,'@'));printf("去除右側(cè)@字符: %s <br>",rtrim($string,'@'));printf("去除兩邊@字符: %s <br>",trim($string,'@'));// 字符串自動(dòng)補(bǔ)齊echo "右邊補(bǔ)齊: " . str_pad($string,50,"-") . "<br>";echo "左邊補(bǔ)齊: " . str_pad($string,50,"-",STR_PAD_LEFT) . "<br>";echo "兩邊補(bǔ)齊: " . str_pad($string,50,"-",STR_PAD_BOTH) . "<br>";// 字符串大小寫轉(zhuǎn)換echo "全部小寫: " . strtolower($string) . "<br>";echo "全部大寫: " . strtoupper($string) . "<br>";echo "首字母大寫: " . ucwords($string) . "<br>";// 反轉(zhuǎn)字符串與MD5echo "反轉(zhuǎn)字符串: " . strrev($string) . "<br>";echo "MD5 加密: " . md5($string) . "<br>"; ?>字符串比較(字節(jié)序): 字節(jié)序比較可以使用strcmp/strcasecmp兩個(gè)函數(shù),只需傳入兩個(gè)字符串即可.
<?php$username="lyshark"; $password="Abc123^";// 不區(qū)分大小寫比較字符串if(strcasecmp(strtolower($username),"lyshark") == 0)printf("用戶名正確.. <br>");// 區(qū)分大小寫驗(yàn)證密碼switch(strcmp($password,"Abc123^")){case 0:echo "兩個(gè)字符串相等.";break;case 1:echo "第一個(gè)大于第二個(gè).";break;case -1:echo "第一個(gè)小于第二個(gè).";break;}// 字符串實(shí)現(xiàn)冒泡排序$info= array("file11.txt","file22.txt","file1.txt","file2.exe");function MySort($array){for($x=0; $x<count($array); $x++)for($y=0;$y<count($array)-1; $y++)if(strnatcmp($array[$y],$array[$y+1])){$tmp = $array[$y];$array[$y] = $array[$y+1];$array[$y+1] = $tmp;}return $array;}print_r(MySort($info)); ?>字符串替換/切割: 將字符串切割為多個(gè)部分,替換字符串,與連接字符串等操作.
<?php// 實(shí)現(xiàn)截取文件后綴function getFileName($url){$location = strrpos($url,"/")+1; // 獲取URL中最后一個(gè)/出現(xiàn)的位置$fileName = substr($url,$location); // 截取從location位置到結(jié)尾的字符return $fileName;}echo getFileName("http://www.baidu.com/index.php") . "<br>";echo getFileName("file://c://windows/php.ini") . "<br>";// 實(shí)現(xiàn)字符串替換$string = "BASH Linux PHP MySQL Ruby Metasploit linux";echo "將Linux替換為Win: " . str_replace("Linux","Windows",$string,$count) . "<br>";echo "將Linux替換為Win: " . str_ireplace("Linux","Windows",$string,$count) . "<br>";$search = array("http","www","jsp","com"); // 搜索字符串$replace = array("https","bbs","php","net"); // 替換字符串$url = "http://www.baidu.com/index.jsp";echo "數(shù)組替換: " . str_replace($search,$replace,$url) . "<br>";// 實(shí)現(xiàn)字符串切割與鏈接$info = "Linux Apache MySQL PHP Web";$str_cat = explode(" ",$info);echo "切割后: " . $str_cat[1] . $str_cat[2] . "<br>";$info = "root:*:0:0::/home/dhat:/bin/bash";list($user,$pass,$uid,$gid,,$home,$shell) = explode(":",$info);echo "切割后: 用戶-> " . $user . " 終端Bash -> " . $shell . "<br>";$info = array("linux","Apache","MySQL","PHP");echo "鏈接字符串: " . implode("+",$info) . "<br>";echo "鏈接字符串: " . join("+",$info) . "<br>"; ?>正則匹配字符串: 通過(guò)使用正則我們同樣可以對(duì)字符串進(jìn)行匹配,切片,組合,查找等操作.
<?php/*郵箱: '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/'正整數(shù): '/^\d+$/'qq號(hào)碼:'/^\d{5,11}$/'手機(jī)號(hào)碼: '/^1(3|4|5|7|8)\d{9}$/'*/// 簡(jiǎn)單的正則匹配方法$pattern = "/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/";$subject = 'aaa 1181506874@qq.com test admin@blib.cn ddd';$recv = preg_match_all($pattern, $subject,$match,PREG_SET_ORDER);echo "匹配記錄: " . $recv . "條, 值: " . $match[0][0] . "," . $match[1][0] . "<br>";// 匹配數(shù)組中符合條件的字符串$array = array("LinuxHat","Nginx 2.2.3","Apache 2.29","PHP");$pattern_version = preg_grep("/^[a-zA-Z ]+(\d|\.)+$/",$array);print_r($pattern_version); echo "<br>";// 正則實(shí)現(xiàn)字符串替換$pattern = "/[!@#$]/";$text = "你@好!,當(dāng)前日#期 01/25/2020 總#共365天";echo "替換特殊符號(hào)為空: " . preg_replace($pattern,"",$text) . "<br>";$pattern = "/(\d{2})\/(\d{2})\/(\d{4})/";echo "替換實(shí)現(xiàn)時(shí)間翻轉(zhuǎn): " . preg_replace($pattern,"\${3}-\${1}-\${2}",$text) . "<br>";// 正則實(shí)現(xiàn)字符串切割$keyworks = preg_split("/[\s,]/","php,nginx, mysql python");echo "切割字符串為數(shù)組: "; print_r($keyworks); echo "<br>";$keyworks = preg_split("//","lyshark",-1,PREG_SPLIT_NO_EMPTY);echo "將字符串切割為字符: "; print_r($keyworks); echo "<br>"; ?>PHP 文件操作
讀文件基本信息: 文件基本信息包括文件類型,文件的創(chuàng)建日期等基本信息,我們可以通過(guò)以下方式來(lái)判斷.
<?php$Path = "C://Windows/System32/drivers/etc/hosts";echo "文件類型: " . filetype($Path) . "<br>";echo "文件建立時(shí)間: " . date("Y年m月j日",filectime($Path))."<br>";echo "文件最后更改時(shí)間: " . date("Y年m月j日",filemtime($Path))."<br>";echo "文件最后打開(kāi)時(shí)間: " . date("Y年m月j日",fileatime($Path))."<br>";if(file_exists($Path))printf("文件存在 <br>");if(is_file($Path))printf("是一個(gè)文件 <br>");if(is_dir($Path))printf("是一個(gè)目錄 <br>");if(is_readable($Path))printf("文件可讀 <br>");if(is_writable($Path))printf("文件可寫 <br>");if(is_executable($Path))printf("文件可執(zhí)行 <br>"); ?>判斷文件類型: 雖然我們可以通過(guò)filetype()函數(shù)判斷文件類型,但是不夠具體,如下是具體的判斷流程.
<?php$Path = "C://Windows/System32/drivers/etc/hosts";function GetFileType($FileName){switch(filetype($FileName)){case "file": $type = "普通文件"; break;case "dir": $type = "目錄文件"; break;case "block": $type = "塊設(shè)備文件"; break;case "fifo": $type = "命名管道文件"; break;case "link": $type = "符號(hào)文件"; break;case "unknown": $type = "未知文件"; break;default: $type = "沒(méi)有檢測(cè)到"; break;}return $type;}$type = GetFileType($Path);printf("文件類型: %s <br>",$type); ?>獲取文件大小: 文件大小的獲取可以使用filesize但此方法需要封裝后才可獲取到常規(guī)單位,代碼如下所示.
<?php$Path = "C://Windows/System32/drivers/etc/hosts";function GetFileSize($bytes){if($bytes >= pow(2,40)){$return = round($bytes/pow(1024,4),2);$suffix = "TB";}else if($bytes >= pow(2,30)){$return = round($bytes/pow(1024,3),2);$suffix = "GB";}else if($bytes >= pow(2,20)){$return = round($bytes/pow(1024,2),2);$suffix = "MB";}else if($bytes >= pow(2,10)){$return = round($bytes/pow(1024,1),2);$suffix = "KB";}else{$return = $bytes;$suffix = "Byte";}return $return . " " . $suffix;}$ret = GetFileSize(filesize($Path));echo "文件實(shí)際大小: " . $ret . "<br>"; ?>文件中的路徑解析: 根據(jù)不同的分隔符,對(duì)文件路徑進(jìn)行解析,解析結(jié)果可以直接使用key-value的方式輸出.
<?php// 返回文件基本信息數(shù)組$Path = "C://Windows/System32/drivers/etc/hosts";$FilePro = stat($Path);echo "文件基本信息: "; print_r(array_slice($FilePro,13)); echo "<br>";// 返回路徑中的 page.php 文件名$Path = "/var/www/html/page.php";echo "帶文件擴(kuò)展名輸出: " . basename($Path) . "<br>";echo "不帶文件擴(kuò)展名輸出: " . basename($Path,".php") . "<br>";// 返回路徑的所在位置echo "文件所在位置: " . dirname($Path) . "<br>";// 返回目錄中文件詳細(xì)信息$path_parts = pathinfo($Path);echo "路徑: " . $path_parts["dirname"] . "<br>";echo "文件: " . $path_parts["basename"] . "<br>";echo "擴(kuò)展名: " . $path_parts["extension"] . "<br>"; ?>文件讀寫操作: 讀寫文件首先需要使用fopen函數(shù)打開(kāi)文件,然后使用fread讀取,fwrite寫入,最后使用fclose釋放句柄.
<?php// 從文件中讀出前100個(gè)字節(jié)$handle = fopen("c://test.log","r") or die("Open File Err");$context = fread($handle,100);echo $context;fclose($handle);// 循環(huán)從文件中讀取全部數(shù)據(jù)$handle = fopen("c://test.log","r") or die("Open File Err");$context = "";while(!feof($handle)){$context = fread($handle,1024);}fclose($handle);echo $context;// 另一種讀取全文的方式$handle = fopen("c://test.log","r") or die("Open File Err");$context = fread($handle,filesize("c://test.log"));fclose($handle);echo $context;// 每次讀入一個(gè)字符,直到讀取結(jié)束$handle = fopen("c://test.log","r") or die("Open File Err");while(false !==($char = fgetc($handle))){echo $char . "<br>";}// 讀取遠(yuǎn)程文件,并輸出$file = fopen("http://www.baidu.com","r");while(!feof($file)){$line = fgets($file,1024);echo $line;}fclose($file);// 文件寫入數(shù)據(jù)$handle = fopen("c://new.txt","w") or die("open file error");for($row=0; $row<10; $row++){fwrite($handle,$row . "www.baidu.com \n");}fclose($handle); ?>遍歷文件目錄: 遍歷目錄中文件,主要用到opendir打開(kāi)為文件,readdir每次讀入一條記錄,最后closedir關(guān)閉句柄.
<?php$Path = "d://";$dir_handle = opendir($Path);echo "<table border='1' width='600' cellspacing='0' cellpadding='0' align='center'>";echo "<caption><h2>目錄: " . $Path . "</h1></caption>";echo "<tr align='left' bgcolor='#ddddddd'>";echo "<th>文件名</th><th>文件大小</th><th>文件類型</th><th>修改時(shí)間</th></tr>";while($each = readdir($dir_handle)){$dir_file_path = $Path . "/" . $each; // 將目錄與文件連接起來(lái)if($num++ % 2 == 0) // 控制奇數(shù)行與偶數(shù)行不同的顏色輸出$bgcolor='#ffccf';else$bgcolor='#ccfff';echo "<tr bgcolor=" . $bgcolor . ">";echo "<td>" . $dir_file_path . "</td>";echo "<td>" . filesize($dir_file_path) . "</td>";echo "<td>" . filetype($dir_file_path) . "</td>";echo "<td>" . date("Y/n/t",filemtime($dir_file_path)) . "</td>";echo "</tr>";}echo "</table>";closedir($dir_handle);echo "目錄: " . $Path . "總共有: " . $num . " 個(gè)文件" . "<br>"; ?>統(tǒng)計(jì)目錄總?cè)萘? 計(jì)算文件磁盤目錄的總大小,具體思路是遞歸遍歷將每次遍歷到的文件大小存入變量遞增.
<?phpecho "磁盤剩余大小: " . disk_free_space("c://") . "<br>";echo "磁盤總計(jì)大小: " . disk_total_space("c://") . "<br>";function GetDirSize($directory){$dir_size = 0;// 首先打開(kāi)目錄,并判斷目錄是否打開(kāi)成功if($dir_handle = @opendir($directory)){// 循環(huán)每次讀入一個(gè)目錄下的所有文件while($filename = readdir($dir_handle)){// 判斷目錄文件,排除. .. 兩個(gè)無(wú)效路徑if($filename != "." && $filename != ".."){$file_path = $directory . "/" . $filename;// 如果是目錄,則需要繼續(xù)遞歸調(diào)用自身函數(shù)if(is_dir($file_path))$dir_size += GetDirSize($file_path);// 如果是文件則統(tǒng)計(jì)大小if(is_file($file_path))$dir_size += filesize($file_path);}}}closedir($dir_handle);return $dir_size;}$dir_size = GetDirSize("D://htmlcss/");echo "目錄大小: " . round($dir_size/pow(1024,2),2). "MB" . "<br>";echo "目錄大小: " . round($dir_size/pow(1024,1),2). "KB" . "<br>"; ?>目錄遞歸拷貝: 如果需要拷貝單個(gè)文件可以直接使用copy函數(shù),如果要拷貝目錄則需要遞歸拷貝.
<?phpfunction CopyFileDir($dir_src,$dir_dst){if(is_file($dir_dst)){printf("目標(biāo)不是目錄,無(wú)法執(zhí)行.");return;}if(!file_exists($dir_dst))mkdir($dir_dst);// 首先打開(kāi)目錄,并判斷目錄是否打開(kāi)成功if($dir_handle = @opendir($dir_src)){// 循環(huán)每次讀入一個(gè)目錄下的所有文件while($filename = readdir($dir_handle)){// 判斷目錄文件,排除. .. 兩個(gè)無(wú)效路徑if($filename != "." && $filename != ".."){$sub_file_src = $dir_src . "/" . $filename;$sub_file_dst = $dir_dst . "/" . $filename;if(is_dir($sub_file_src))CopyFileDir($sub_file_src,$sub_file_dst);if(is_file($sub_file_src))copy($sub_file_src,$sub_file_dst);}}closedir($dir_handle);}return $dir_size;}// 將d://test目錄,拷貝到c://testCopyFileDir("d://test","c://test"); ?>目錄遞歸刪除: 遞歸刪除需要先調(diào)用unlink函數(shù)將目錄中每個(gè)文件都刪掉,然后贊調(diào)用rmdir刪除空目錄.
<?phpfunction DelFileDir($directory){// 判斷目錄是否存在if(file_exists($directory)){if($dir_handle = @opendir($directory)){while($filename = readdir($dir_handle)){if($filename!='.' && $filename != ".."){$sub_file = $directory . "/" . $filename;if(is_dir($sub_file))DelFileDir($sub_file);if(is_file($sub_file))unlink($sub_file);}}closedir($dir_handle);rmdir($directory);}}}// 刪除c://test整個(gè)目錄DelFileDir("c://test"); ?>PHP 操作數(shù)據(jù)庫(kù)
創(chuàng)建測(cè)試數(shù)據(jù): 首先我們需要?jiǎng)?chuàng)建一些測(cè)試記錄,然后先來(lái)演示一下數(shù)據(jù)庫(kù)的基本的鏈接命令的使用.
create table username ( uid int not null,name varchar(50),sex varchar(10),age int );insert into username(uid,name,sex,age) values(1,"李四","男",25); insert into username(uid,name,sex,age) values(2,"張三","男",33); insert into username(uid,name,sex,age) values(3,"王五","女",56); insert into username(uid,name,sex,age) values(4,"王二麻子","男",76); insert into username(uid,name,sex,age) values(5,"六頭","男",34); insert into username(uid,name,sex,age) values(6,"孫琪","女",25); insert into username(uid,name,sex,age) values(7,"流云","男",63);<?php$mysqli = new mysqli("localhost","root","123456","mysql");if(mysqli_connect_errno()){printf("連接失敗: %s <br>",mysqli_connect_error());}printf("當(dāng)前數(shù)據(jù)庫(kù)字符集: %s <br>",$mysqli->character_set_name());printf("客戶端版本: %s <br>",$mysqli->get_client_info());printf("主機(jī)信息: %s <br>",$mysqli->host_info);printf("服務(wù)器版本: %s <br>",$mysqli->server_info);printf("服務(wù)器版本: %s <br>",$mysqli->server_version);if($mysqli->query("select * from lyshark.username;")){echo "當(dāng)前記錄條數(shù): {$mysqli->affected_rows} 條 <br>";echo "新插入的ID值: {$mysqli->insert_id} 條 <br>";}$mysqli->close(); ?>逐條讀取數(shù)據(jù): 通過(guò)循環(huán)的方式逐條讀取數(shù)據(jù),并將數(shù)據(jù)根據(jù)HTML格式輸出到屏幕,注意用完后釋放,否則會(huì)非常占用內(nèi)存.
<?php$mysqli = new mysqli("localhost","root","123456","lyshark");if(mysqli_connect_errno())printf("連接失敗: %s <br>",mysqli_connect_error());if(!$mysqli->query("set names utf8;"))printf("切換字符集失敗 <br>");// 第一種查詢方式: 逐行遍歷結(jié)果集$result = $mysqli->query("select uid,name from lyshark.username;");while(list($uid,$name) = $result->fetch_row()){echo "UID: {$uid} --> Name: {$name} <br>";}$result->close();// 第二種遍歷方式: 遍歷時(shí)直接輸出到外部表格上$result = $mysqli->query("select * from lyshark.username;");echo "<table width='90%' border='1' align='center'>";echo "<th>用戶ID</th><th>姓名</th><th>性別</th><th>年齡</th>";while($row=$result->fetch_assoc()){echo "<tr align='center'>";echo "<td> {$row['uid']}</td>";echo "<td> {$row['name']}</td>";echo "<td> {$row['sex']}</td>";echo "<td> {$row['age']}</td>";echo "<tr>";}echo "</table>";$result->close();//第三種方式,直接輸出關(guān)聯(lián)數(shù)組$result = $mysqli->query("select * from lyshark.username;");while($row=$result->fetch_array(MYSQLI_ASSOC)){echo "UID: {$row['uid']} 姓名: {$row['name']} <br>";}$result->close();$mysqli->close(); ?>通過(guò)對(duì)象返回結(jié)果集: 該方法與前面三個(gè)不同,他將以一個(gè)對(duì)象的形式返回一條結(jié)果記錄,而不是數(shù)組,它的每個(gè)字段都需要以對(duì)象的方式進(jìn)行訪問(wèn),數(shù)據(jù)列的名稱區(qū)分字母大小寫.
<?php$mysqli = new mysqli("localhost","root","123456","lyshark");if(mysqli_connect_errno())printf("連接失敗: %s <br>",mysqli_connect_error());if(!$mysqli->query("set names utf8;"))printf("切換字符集失敗 <br>");$result = $mysqli->query("select * from lyshark.username;");echo "<table width='90%' border='1' align='center'>";echo "<th>用戶ID</th><th>姓名</th><th>性別</th><th>年齡</th>";while($rowObj=$result->fetch_object()){echo "<tr align='center'>";echo "<td> {$rowObj->uid}</td>";echo "<td> {$rowObj->name}</td>";echo "<td> {$rowObj->sex}</td>";echo "<td> {$rowObj->age}</td>";echo "<tr>";}echo "</table>";$result->close();$mysqli->close(); ?>參數(shù)綁定執(zhí)行: 參數(shù)綁定執(zhí)行其實(shí)使用的就是預(yù)處理技術(shù),即預(yù)先定義SQL語(yǔ)句模板,然后后期使用變量對(duì)模板進(jìn)行填充,然后在帶入數(shù)據(jù)庫(kù)執(zhí)行,這里其實(shí)可以在帶入模板時(shí)對(duì)數(shù)據(jù)進(jìn)行合法驗(yàn)證,保證不會(huì)出現(xiàn)SQL注入的現(xiàn)象.
<?php$mysqli = new mysqli("localhost","root","123456","lyshark");if(mysqli_connect_errno())printf("連接失敗: %s <br>",mysqli_connect_error());if(!$mysqli->query("set names utf8;"))printf("切換字符集失敗 <br>");// 聲明一個(gè)insert語(yǔ)句,并使用mysqli->prepare($query)對(duì)該SQL進(jìn)行預(yù)處理$query = "insert into username(uid,name,sex,age) values(?,?,?,?);";$stmt = $mysqli->prepare($query);// 使用占位符綁定變量: i=>整數(shù) d=>浮點(diǎn)數(shù) s=>字符串 b=>二進(jìn)制// issi => 代表 => 整數(shù) 字符串 字符串 整數(shù)$stmt->bind_param("issi",$u_id,$u_name,$u_sex,$u_age);// 填充預(yù)處理變量$u_id = 8;$u_name = "lyshark";$u_sex = "男";$u_age = 25;$stmt->execute(); // 執(zhí)行插入操作echo "插入的行數(shù): {$stmt->affected_rows} <br>";echo "自動(dòng)增長(zhǎng)ID: {$mysqli->insert_id} <br>";// 繼續(xù)填充插入新的變量$u_id = 10;$u_name = "super_user";$u_sex = "男";$u_age = 300;$stmt->execute(); // 執(zhí)行插入操作echo "插入的行數(shù): {$stmt->affected_rows} <br>";echo "自動(dòng)增長(zhǎng)ID: {$mysqli->insert_id} <br>";$stmt->close();$mysqli->close(); ?>預(yù)處理語(yǔ)句查詢: 使用預(yù)處理執(zhí)行SQL時(shí),拿到的執(zhí)行結(jié)果并不是一個(gè)數(shù)組,我們需要自己將這些結(jié)果集綁定到指定的變量上,然后再通過(guò)遍歷變量的方式獲取到結(jié)果集中的所有數(shù)據(jù).
<?php$mysqli = new mysqli("localhost","root","123456","lyshark");if(mysqli_connect_errno())printf("連接失敗: %s <br>",mysqli_connect_error());if(!$mysqli->query("set names utf8;"))printf("切換字符集失敗 <br>");$query = "select uid,name,sex,age from lyshark.username;";if($res = $mysqli->prepare($query)){$res->execute(); // 執(zhí)行SQL語(yǔ)句$res->store_result(); // 取回所有的查詢結(jié)果echo "記錄個(gè)數(shù): {$res->num_rows} 行 <br>";// 綁定返回結(jié)果到指定變量上$res->bind_result($u_id,$u_name,$u_sex,$u_age);while($res->fetch()){printf("%d --> %s --> %s --> %d <br>",$u_id,$u_name,$u_sex,$u_age);}}$res->close();$mysqli->close(); ?>如果在SELECT查詢語(yǔ)句上也使用占位符去查詢,并需要多次執(zhí)行這一條語(yǔ)句時(shí),也可以將mysqli_stmt對(duì)象中的bind_param()和bind_result()方法結(jié)合起來(lái).
<?php$mysqli = new mysqli("localhost","root","123456","lyshark");if(mysqli_connect_errno())printf("連接失敗: %s <br>",mysqli_connect_error());if(!$mysqli->query("set names utf8;"))printf("切換字符集失敗 <br>");// 此處我們使用一個(gè)占位符uid=?$query = "select uid,name,sex,age from lyshark.username where uid=?;";if($res = $mysqli->prepare($query)) // 預(yù)處理語(yǔ)句{$u_id = 1;$res->bind_param("d",$u_id); // 綁定參數(shù),綁定到UID上$res->execute(); // 執(zhí)行$res->store_result(); // 取回所有的查詢結(jié)果echo "記錄個(gè)數(shù): {$res->num_rows} 行 <br>";// 綁定返回結(jié)果到指定變量上$res->bind_result($u_id,$u_name,$u_sex,$u_age);while($res->fetch()){printf("%d --> %s --> %s --> %d <br>",$u_id,$u_name,$u_sex,$u_age);}}$res->close();$mysqli->close(); ?>開(kāi)啟事務(wù)提交: 在使用事務(wù)提交時(shí)需要讓MySQL數(shù)據(jù)庫(kù)切換到InnoDB上,然后執(zhí)行事務(wù),最后提交.
<?php$mysqli = new mysqli("localhost","root","123456","lyshark");if(mysqli_connect_errno())printf("連接失敗: %s <br>",mysqli_connect_error());if(!$mysqli->query("set names utf8;"))printf("切換字符集失敗 <br>");$success = TRUE;$age = 30;$mysqli->autocommit(0); // 暫時(shí)關(guān)閉事務(wù)提交$result = $mysqli->query("select * from lyshark.username;");// 如果SQL執(zhí)行失敗,則將狀態(tài)設(shè)置為假if(!$result or $mysqli->affected_rows != 1){$success=FALSE;}// 最后判斷是否成功,成功則提交事務(wù)if($success){$mysqli->commit();echo "事務(wù)已提交 <br>";}else{$mysqli->rollback();echo "事務(wù)執(zhí)行失敗,回滾到初始狀態(tài)<br>";}$mysqli->autocommit(1); // 開(kāi)啟事務(wù)$result->close();$mysqli->close(); ?>PDO 連接MySQL數(shù)據(jù)庫(kù): PDO技術(shù)就是在SQL語(yǔ)句中添加了一個(gè)中間層,所有的查詢方式都可以通過(guò)中間層去調(diào)用,極大的提高了數(shù)據(jù)庫(kù)操作的通用性,同時(shí)安全性也得到了更好的保障,以下是基本的語(yǔ)句使用:
<?php// 設(shè)置持久連接的選項(xiàng)數(shù)組作為最后一個(gè)參數(shù)$opt = array(PDO::ATTR_PERSISTENT => TRUE);try{$dbh = new PDO("mysql:dbname=lyshark;host=localhost","root","123456",$opt);}catch(PDOException $e){echo "數(shù)據(jù)庫(kù)連接失敗: {$e->getMessage()} <br>";exit;}// 調(diào)用getAttribute()可以獲得所有屬性名稱對(duì)應(yīng)的值.echo "是否關(guān)閉自動(dòng)提交: " . $dbh->getAttribute(PDO::ATTR_AUTOCOMMIT) . "<br>";echo "PDO錯(cuò)誤處理模式: " . $dbh->getAttribute(PDO::ATTR_ERRMODE) . "<br>";echo "表字段字符的大小寫轉(zhuǎn)換: " . $dbh->getAttribute(PDO::ATTR_CASE) . "<br>";echo "連接狀態(tài)相關(guān)的信息: " . $dbh->getAttribute(PDO::ATTR_CONNECTION_STATUS) . "<br>";echo "空字符串轉(zhuǎn)換SQL的NULL: " . $dbh->getAttribute(PDO::ATTR_ORACLE_NULLS) . "<br>";echo "應(yīng)用程序提前獲取數(shù)據(jù)大小: " . $dbh->getAttribute(PDO::ATTR_PERSISTENT) . "<br>";// 設(shè)置一個(gè)標(biāo)志$dbh->setAttribute(PDO::ATTR_ERRMODE); ?>PDO 獲取表中數(shù)據(jù): 當(dāng)執(zhí)行查詢語(yǔ)句時(shí)我們可以使用PDO中的Query()方法,該方法執(zhí)行后返回受影響的行總數(shù),也可以使用Fetch等語(yǔ)句,下面是三者的查詢方式.
<?php// 設(shè)置持久連接的選項(xiàng)數(shù)組作為最后一個(gè)參數(shù)$opt = array(PDO::ATTR_PERSISTENT => TRUE);try{$dbh = new PDO("mysql:dbname=lyshark;host=localhost","root","123456",$opt);// 設(shè)置捕獲異常$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);}catch(PDOException $e){echo "數(shù)據(jù)庫(kù)連接失敗: {$e->getMessage()} <br>";exit;} // -------------------------------------------------// 使用 query() 完成數(shù)據(jù)查詢$query = "select uid,name,sex,age from username";try{$pdo_proc = $dbh->query($query);echo "總共查詢到: {$pdo_proc->rowCount()} 條記錄 <br>";foreach($pdo_proc as $row){echo $row['uid'] . "\t";echo $row['name'] . "\t";echo $row['sex'] . "\t";echo $row['age'] . "\t";echo "<br>";}}catch(PDOException $e){// 兩種方式都可以完成異常捕獲echo $e->getMessage();print_r($dbh->errorInfo());}// -------------------------------------------------// 使用 fetch() 方法完成遍歷$stmt = $dbh->query("select uid,name,sex,age from username");while($row = $stmt->fetch(PDO::FETCH_ASSOC)){echo $row['uid'] . "\t";echo $row['name'] . "\t";echo $row['sex'] . "\t";echo $row['age'] . "\t";echo "<br>";}// -------------------------------------------------// 使用 fetch_all() 方法完成遍歷$stmt = $dbh->prepare("select uid,name,sex,age from username;");$stmt->execute();$allRow = $stmt->fetchAll(PDO::FETCH_NUM);foreach ($allRow as $row){echo "{$row[0]} <br>";} ?>PDO 參數(shù)綁定后執(zhí)行: 參數(shù)綁定執(zhí)行,在上面的內(nèi)容中已經(jīng)嘗試過(guò)了,這里其實(shí)就是使用的引擎變成了PDO引擎,根本的東西還是老樣子.
<?php// 設(shè)置持久連接的選項(xiàng)數(shù)組作為最后一個(gè)參數(shù)$opt = array(PDO::ATTR_PERSISTENT => TRUE);try{$dbh = new PDO("mysql:dbname=lyshark;host=localhost","root","123456",$opt);// 設(shè)置捕獲異常$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);}catch(PDOException $e){echo "數(shù)據(jù)庫(kù)連接失敗: {$e->getMessage()} <br>";exit;}// 直接綁定后插入數(shù)據(jù)$query = "insert into username(uid,name,sex,age) values(?,?,?,?);";$stmt = $dbh->prepare($query); // 預(yù)處理// 填充數(shù)據(jù)$u_id = 100;$u_name = "lyshark";$u_sex = "男";$u_age = 25;// 綁定參數(shù),分別綁定1,2,3,4個(gè)位置的?號(hào),到每個(gè)變量上$stmt->bindParam(1,$u_id);$stmt->bindParam(2,$u_name);$stmt->bindParam(3,$u_sex);$stmt->bindParam(4,$u_age);$stmt->execute(); // 執(zhí)行提交// -------------------------------------------------// 第二種綁定參數(shù)的方式$query = "insert into username(uid,name,sex,age) values(:u_id,:u_name,:u_sex,:u_age);";$stmt = $dbh->prepare($query);$stmt->execute(array(":u_id" => 200,":u_name"=> "三從",":u_sex" => "女",":u_age"=>25)); ?>PDO 綁定參數(shù)實(shí)現(xiàn)查詢: 前面的查詢是直接寫死的SQL語(yǔ)句實(shí)現(xiàn)的查詢,這里我們需要通過(guò)PDO將其參數(shù)綁定,動(dòng)態(tài)的傳入數(shù)據(jù)讓其進(jìn)行查詢,該方法可以將一個(gè)列和一個(gè)指定的變量名綁定在一起.
<?php// 設(shè)置持久連接的選項(xiàng)數(shù)組作為最后一個(gè)參數(shù)$opt = array(PDO::ATTR_PERSISTENT => TRUE);try{$dbh = new PDO("mysql:dbname=lyshark;host=localhost","root","123456",$opt);// 設(shè)置捕獲異常$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);}catch(PDOException $e){echo "數(shù)據(jù)庫(kù)連接失敗: {$e->getMessage()} <br>";exit;}$query = "select uid,name,sex,age from username;";try{$stmt = $dbh->prepare($query);$stmt->execute();$stmt->bindColumn(1,$u_id); // 通過(guò)序號(hào)綁定$stmt->bindColumn(2,$u_name); // 第二個(gè)參數(shù)綁定到u_name$stmt->bindColumn('sex',$u_sex); // 將sex綁定到u_sex$stmt->bindColumn('age',$u_age);while($row = $stmt->fetch(PDO::FETCH_BOUND)){echo "ID: {$u_id} --> Name: {$u_name} <br>";}}catch(PDOException $e){echo $e->getMessage();} ?>PDO 開(kāi)啟事務(wù)支持: PDO技術(shù)同樣支持十五處理,事務(wù)用于保證,數(shù)據(jù)的原子性,一致性,獨(dú)立性,持久性,也就是ACID模型.
<?php// 設(shè)置持久連接的選項(xiàng)數(shù)組作為最后一個(gè)參數(shù)$opt = array(PDO::ATTR_PERSISTENT => TRUE);try{$dbh = new PDO("mysql:dbname=lyshark;host=localhost","root","123456",$opt);// 設(shè)置捕獲異常$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);}catch(PDOException $e){echo "數(shù)據(jù)庫(kù)連接失敗: {$e->getMessage()} <br>";exit;}try{$dbh->beginTransaction(); // 啟動(dòng)一個(gè)事務(wù)$dbh->exec("select * from username;");$dbh->commit(); // 提交事務(wù)}catch(Exception $e){$dbh->rollBack();echo "事務(wù)失敗,自動(dòng)回滾: " . $e->getMessage() . "<br>";} ?>總結(jié)
以上是生活随笔為你收集整理的PHP 开发基础知识笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python写通讯录_Python:利用
- 下一篇: php循环输出数组 json,php循环