你在mysql_*中是這樣作的php
1 <?php 2 $result = mysql_query('SELECT * from table') or die(mysql_error()); 3 4 $num_rows = mysql_num_rows($result); 5 6 while($row = mysql_fetch_assoc($result)) { 7 echo $row['field1']; 8 }
你在pdo中能夠這個樣mysql
<?php $stmt = $db->query('SELECT * FROM table'); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo $row['field1']; }
或者sql
<?php $result = mysql_query('SELECT * from table') or die(mysql_error()); $num_rows = mysql_num_rows($result); while($row = mysql_fetch_assoc($result)) { echo $row['field1']; }
提示:若是你使用了方法像query()。這個方法返回一個PDOStatement 對象,若是你想取出結果,請這樣使用:數據庫
<?php foreach($db->query('SELECT * FROM table') as $row) { echo $row['field1']; }
PDO數據是經過->fetch() 方法得到的,這個方法是你的statement處理的。
在fetch以前。最好告訴PDO這個數據你打算怎麼fetch。在下個章節我會解釋。編程
PDO::FETCH_ASSOC 能夠在fetch() 和 fetchAll()中使用。 這個告訴PDO返回關聯數組,字段的名字做爲key。這還有不少fench方法。數組
首先我說明怎麼選擇fench 模式。安全
$stmt->fetch(PDO::FETCH_ASSOC)
在這裏我用的是fetch,你也能夠用:app
下面討論fetch模式函數
獲取行的數量
不是經過mysql_num_rows 而是經過rowCount(),好比說:fetch
<?php $stmt = $db->query('SELECT * FROM table'); $row_count = $stmt->rowCount(); echo $row_count.' rows selected';
獲取插入的id
<?php $result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')"); $insertId = $db->lastInsertId();
在mysql_*中咱們是這樣作的
<?php $results = mysql_query("UPDATE table SET field='value'") or die(mysql_error()); echo mysql_affected_rows($result);
在PDO中,一樣能夠這樣:
<?php $affected_rows = $db->exec("UPDATE table SET field='value'"); echo $affected_rows;
在上面的語句中,執行了一個sql語句而且返回受影響的行數。
上面的方法在你查詢語句中沒有變量時很好用。若是有變量,就應該使用 prepared statement or parameterized statement 。
Q:什麼是 Prepared Statements,我爲何要用他?
A:Prepared Statement 是一條預編譯的sql語句,能夠被執行屢次。
典型的使用Prepared Statement 工做流:
INSERT INTO PRODUCT (name, price) VALUES (?, ?)
DBMS進行解析、編譯,獲得最優的語句,把結果(語句)儲存起來,並不執行。
執行。事後,程序爲參數提供或綁定值,DBMS執行語句(通常會返回一個結果)。程序或許會執行屢次由於它有不一樣的值,想得到不一樣的結果。咱這個例子裏,把Bread做爲第一個參數,1.00做爲第二個參數。
你能夠經過引入佔位符使用預編譯語句。
Q:什麼是命名佔位符(named placeholders ),怎麼使用呢?
A:命名佔位符,用過一個冒號而不是? 這樣就不用去操心問號的順序問題了
$stmt->bindParam(':bla', $bla);
<?php $stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name"); $stmt->execute(array(':name' => $name, ':id' => $id)); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
另外一個對於OOP(面向對象編程)很友好的就是,命名佔位符能夠直接插入到你的對象,再而後加入到你的數據庫。假設屬性與字段相同
class person { public $name; public $add; function __construct($a,$b) { $this->name = $a; $this->add = $b; } } $demo = new person('john','29 bla district'); $stmt = $db->prepare("INSERT INTO table (name, add) value (:name, :add)"); $stmt->execute((array)$demo);
Q:好了,什麼是匿名佔位符(unnamed placeholders),怎麼使用?
A:看個例子。
<?php $stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)"); $stmt->bindValue(1, $name, PDO::PARAM_STR); $stmt->bindValue(2, $add, PDO::PARAM_STR); $stmt->execute(); $stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)"); $stmt->execute(array('john', '29 bla district'));
注意:在匿名佔位符咱們必定要注意在數組中的順序,在PDOStatement::execute() 方法中。
$stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name"); $stmt->execute(array(':name' => $name, ':id' => $id)); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $db->prepare("INSERT INTO table(field1,field2) VALUES(:field1,:field2)"); $stmt->execute(array(':field1' => $field1, ':field2' => $field2)); $affected_rows = $stmt->rowCount();
$stmt = $db->prepare("DELETE FROM table WHERE id=:id"); $stmt->bindValue(':id', $id, PDO::PARAM_STR); $stmt->execute(); $affected_rows = $stmt->rowCount();
$stmt = $db->prepare("UPDATE table SET name=? WHERE id=?"); $stmt->execute(array($name, $id)); $affected_rows = $stmt->rowCount();
注意:
PDO和Mysqli也不是徹底的安全。有機會會翻譯一遍這個文章,這裏就簡單說一下:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $pdo->query('SET NAMES GBK'); $stmt = $pdo->prepare("SELECT * FROM test WHERE name = ? LIMIT 1"); $stmt->execute(array(chr(0xbf) . chr(0x27) . " OR 1=1 /*"));
下面是一個封裝的類
1 class CPdo{ 2 protected $_dsn = "mysql:host=localhost;dbname=test"; 3 protected $_name = "root"; 4 protected $_pass = ""; 5 protected $_condition = array(); 6 protected $pdo; 7 protected $fetchAll; 8 protected $query; 9 protected $result; 10 protected $num; 11 protected $mode; 12 protected $prepare; 13 protected $row; 14 protected $fetchAction; 15 protected $beginTransaction; 16 protected $rollback; 17 protected $commit; 18 protected $char; 19 private static $get_mode; 20 private static $get_fetch_action; 21 /** 22 *pdo construct 23 */ 24 public function __construct($pconnect = false) { 25 $this->_condition = array(PDO::ATTR_PERSISTENT => $pconnect); 26 $this->pdo_connect(); 27 } 28 /** 29 *pdo connect 30 */ 31 private function pdo_connect() { 32 try{ 33 $this->pdo = new PDO($this->_dsn,$this->_name,$this->_pass,$this->_condition); 34 } 35 catch(Exception $e) { 36 return $this->setExceptionError($e->getMessage(), $e->getline, $e->getFile); 37 } 38 } 39 /** 40 *self sql get value action 41 */ 42 public function getValueBySelfCreateSql($sql, $fetchAction = "assoc",$mode = null) { 43 $this->fetchAction = $this->fetchAction($fetchAction); 44 $this->result = $this->setAttribute($sql, $this->fetchAction, $mode); 45 $this->AllValue = $this->result->fetchAll(); 46 return $this->AllValue; 47 } 48 /** 49 *select condition can query 50 */ 51 private function setAttribute($sql, $fetchAction, $mode) { 52 $this->mode = self::getMode($mode); 53 $this->fetchAction = self::fetchAction($fetchAction); 54 $this->pdo->setAttribute(PDO::ATTR_CASE, $this->mode); 55 $this->query = $this->base_query($sql); 56 $this->query->setFetchMode($this->fetchAction); 57 return $this->query; 58 } 59 /** 60 *get mode action 61 */ 62 private static function getMode($get_style){ 63 switch($get_style) { 64 case null: 65 self::$get_mode = PDO::CASE_NATURAL; 66 break; 67 case true: 68 self::$get_mode = PDO::CASE_UPPER; 69 break; 70 case false; 71 self::$get_mode= PDO::CASE_LOWER; 72 break; 73 } 74 return self::$get_mode; 75 } 76 /** 77 *fetch value action 78 */ 79 private static function fetchAction($fetchAction) { 80 switch($fetchAction) { 81 case "assoc": 82 self::$get_fetch_action = PDO::FETCH_ASSOC; //asso array 83 break; 84 case "num": 85 self::$get_fetch_action = PDO::FETCH_NUM; //num array 86 break; 87 case "object": 88 self::$get_fetch_action = PDO::FETCH_OBJ; //object array 89 break; 90 case "both": 91 self::$get_fetch_action = PDO::FETCH_BOTH; //assoc array and num array 92 break; 93 default: 94 self::$get_fetch_action = PDO::FETCH_ASSOC; 95 break; 96 } 97 return self::$get_fetch_action; 98 } 99 /** 100 *get total num action 101 */ 102 public function rowCount($sql) { 103 $this->result = $this->base_query($sql); 104 $this->num = $this->result->rowCount(); 105 return $this->num; 106 } 107 /* 108 *simple query and easy query action 109 */ 110 public function query($table, $column = "*",$condition = array(), $group = "",$order = "", $having = "", $startSet = "",$endSet = "",$fetchAction = "assoc",$params = null){ 111 $sql = "select ".$column." from `".$table."` "; 112 if ($condition != null) { 113 foreach($condition as $key=>$value) { 114 $where .= "$key = '$value' and "; 115 } 116 $sql .= "where $where"; 117 $sql .= "1 = 1 "; 118 } 119 if ($group != "") { 120 $sql .= "group by ".$group." "; 121 } 122 if ($order != "") { 123 $sql .= " order by ".$order." "; 124 } 125 if ($having != "") { 126 $sql .= "having '$having' "; 127 } 128 if ($startSet != "" && $endSet != "" && is_numeric($endSet) && is_numeric($startSet)) { 129 $sql .= "limit $startSet,$endSet"; 130 } 131 $this->result = $this->getValueBySelfCreateSql($sql, $fetchAction, $params); 132 return $this->result; 133 } 134 /** 135 *execute delete update insert and so on action 136 */ 137 public function exec($sql) { 138 $this->result = $this->pdo->exec($sql); 139 $substr = substr($sql, 0 ,6); 140 if ($this->result) { 141 return $this->successful($substr); 142 } else { 143 return $this->fail($substr); 144 } 145 } 146 /** 147 *prepare action 148 */ 149 public function prepare($sql) { 150 $this->prepare = $this->pdo->prepare($sql); 151 $this->setChars(); 152 $this->prepare->execute(); 153 while($this->rowz = $this->prepare->fetch()) { 154 return $this->row; 155 } 156 } 157 /** 158 *USE transaction 159 */ 160 public function transaction($sql) { 161 $this->begin(); 162 $this->result = $this->pdo->exec($sql); 163 if ($this->result) { 164 $this->commit(); 165 } else { 166 $this->rollback(); 167 } 168 } 169 /** 170 *start transaction 171 */ 172 private function begin() { 173 $this->beginTransaction = $this->pdo->beginTransaction(); 174 return $this->beginTransaction; 175 } 176 /** 177 *commit transaction 178 */ 179 private function commit() { 180 $this->commit = $this->pdo->commit(); 181 return $this->commit; 182 } 183 /** 184 *rollback transaction 185 */ 186 private function rollback() { 187 $this->rollback = $this->pdo->rollback(); 188 return $this->rollback; 189 } 190 /** 191 *base query 192 */ 193 private function base_query($sql) { 194 $this->setChars(); 195 $this->query = $this->pdo->query($sql); 196 return $this->query; 197 } 198 /** 199 *set chars 200 */ 201 private function setChars() { 202 $this->char = $this->pdo->query("SET NAMES 'UTF8'"); 203 return $this->char; 204 } 205 /** 206 *process sucessful action 207 */ 208 private function successful($params){ 209 return "The ".$params." action is successful"; 210 } 211 /** 212 *process fail action 213 */ 214 private function fail($params){ 215 return "The ".$params." action is fail"; 216 } 217 /***進程異常動做 218 *process exception action 219 */ 220 private function setExceptionError($getMessage, $getLine ,$getFile) { 221 echo "Error message is ".$getMessage."<br /> The Error in ".$getLine." line <br /> This file dir on ".$getFile; 222 exit(); 223 } 224 }
封裝類2
1 <?php 2 /** 3 */ 4 5 //使用pdo鏈接數據庫 封裝增刪改查 6 7 class DB{ 8 9 //定義私有屬性 10 private $host; 11 private $port; 12 private $username; 13 private $password; 14 private $dbname; 15 private $charset; 16 private $dbtype; 17 private $pdo; 18 19 //定義構造函數自動加載配置文件 20 function __construct(){ 21 //加載配置文件 22 include_once('./config/config.php'); 23 24 //給屬性賦值 25 $this->dbtype = $config['db']; 26 $this->host = $config['host']; 27 $this->username = $config['username']; 28 $this->password = $config['password']; 29 $this->charset = $config['charset']; 30 $this->port = $config['port']; 31 $this->dbname = $config['dbname']; 32 33 //pdo鏈接數據庫 34 $this->pdo = new PDO("$this->dbtype:host=$this->host;dbname=$this->dbname","$this->username","$this->password"); 35 //發送編碼 36 $this->pdo->query("set names $this->charset"); 37 } 38 39 /** 40 * 定義執行查詢sql語句的方法 41 * 參數: 查詢sql語句 42 * 返回: 二維關聯數組 43 */ 44 public function query($sql){ 45 $res = $this->pdo->query($sql); 46 $res->setFetchMode(PDO::FETCH_ASSOC); 47 $arr = $res->fetchAll(); 48 return $arr; 49 } 50 51 52 /** 53 * 查詢一行記錄的方法 54 * 參數:表名 條件(不包含where) 55 * 返回:一維關聯數組 56 */ 57 public function getRow($tablename,$where){ 58 //組裝sql語句 59 $sql = "select * from $tablename where $where"; 60 //查詢 61 $res = $this->pdo->query($sql); 62 $res->setFetchMode(PDO::FETCH_ASSOC); 63 $arr = $res->fetch(); 64 return $arr; 65 } 66 67 68 /** 69 * 查詢所有記錄 70 * 參數:表名 71 * 返回:二維關聯數組 72 */ 73 public function getAll($tablename){ 74 $res = $this->pdo->query("select * from $tablename"); 75 $res->setFetchMode(PDO::FETCH_ASSOC); 76 $arr = $res->fetchAll(); 77 return $arr; 78 } 79 80 /** 81 * 查詢某個字段 82 * 參數: 字段名(多個的話用逗號隔開) 表名 條件(不含where) 83 * 返回: 二維關聯數組 84 */ 85 public function getOne($column,$tablename,$where="1"){ 86 //拼接sql語句 87 $sql = "select $column from $tablename where $where"; 88 $rs = $this->pdo->query($sql); 89 $rs->setFetchMode(PDO::FETCH_ASSOC); 90 //$col = $rs->fetchColumn(); 91 $col = $rs->fetchAll(); 92 return $col; 93 } 94 95 96 /** 97 * 查詢最後一次插入的數據 98 * 參數:表名 99 * 返回:數組 100 */ 101 public function getlastone($tablename){ 102 $sql = "select * from $tablename where id=(select max(id) from $tablename)"; 103 $res = $this->pdo->query($sql); 104 $res->setFetchMode(PDO::FETCH_ASSOC); 105 $arr = $res->fetch(); 106 return $arr; 107 } 108 109 110 /** 111 * 向數據庫中添加一條信息 112 * 參數:表名 一維關聯數組 113 * 返回: 布爾值 114 */ 115 public function insert($tablename,$arr){ 116 //拿到數組以後先處理數組 過濾字段 117 //取出表中的字段 118 $sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = '$tablename' and table_schema ='$this->dbname'"; 119 $columns = $this->pdo->query($sql); 120 $columns->setFetchMode(PDO::FETCH_ASSOC); 121 $columns = $columns->fetchAll(); 122 $cols = array(); //存儲表中的所有字段 123 foreach($columns as $key=>$val){ 124 $cols[] = $val['COLUMN_NAME']; 125 } 126 //將要入庫的數組進行鍵值分離 127 $keys = array(); 128 $values = ''; 129 foreach($arr as $k=>$v){ 130 if(!in_array($k,$cols)){ 131 unset($arr[$k]); 132 }else{ 133 $keys[] = $k; 134 $values .= "'".$v."',"; 135 } 136 } 137 $column = implode(',',$keys); 138 $values = substr($values,0,-1); 139 //拼接sql語句 140 $sql = "insert into $tablename($column) values ($values)"; 141 $res = $this->pdo->exec($sql); 142 return $res; 143 } 144 145 146 /** 147 * 刪除數據 其實就是改變字段值使之不被查詢 148 * 參數:表名 條件(不含where) 149 * 返回:布爾 150 */ 151 public function delete($tablename,$where){ 152 $sql = "update $tablename set is_del=1 where $where"; 153 $res = $this->pdo->exec($sql); 154 return $res; 155 } 156 157 158 /** 159 * 修改數據 160 * 參數:表名 要修改的數據的數組 161 * 返回:布爾 162 */ 163 public function update($tablename,$arr,$where){ 164 //處理傳過來的數組 165 $str = ""; 166 foreach($arras $k=>$v){ 167 $str .= "$k='".$v."',"; 168 } 169 //截取字符串 170 $str = substr($str,0,-1); 171 //拼接sql語句 172 $sql = "update $tablename set $str where $where"; 173 $res = $this->pdo->exec($sql); 174 return $res; 175 } 176 }