用PHP的PDO方法操作MySQL資料庫方法(查詢 更新 刪除)
阿新 • • 發佈:2019-01-02
用PHP連線MYSQL資料庫有3種方法:
第一種方法是:MySQL
API 大部分擴充套件自 PHP 5.5.0 起已廢棄,並在將來會被移除。應使用 MySQLi或 PDO_MySQL 擴充套件來替換之。
參考:
http://www.cnblogs.com/CraryPrimitiveMan/p/4385034.html
已經寫的很詳細了
第二種方法是:
使用MySQLi類
http://www.cnblogs.com/52fhy/p/5352304.html
這個也已經寫的很詳細了。
第三種方法是:
使用PDO
參考:寫的很好
http://www.cnblogs.com/52fhy/p/5352304.html感謝作者原創。謝謝。
我主要是學習第三種PDO方法,大部分也是參考上面這篇文章。稍作修改。
先建立資料庫。複製程式碼到TXT檔案,然後另存為'建立資料庫.txt' 最後修改為'建立資料庫.sql',最後用navicat執行資料庫檔案。就建好資料庫了。
程式碼如下:
CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(25) NOT NULL DEFAULT '', `gender` tinyint(1) NOT NULL DEFAULT '1', `age` int(11) NOT NULL DEFAULT '0', `flag` tinyint(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; /*Data for the table `user` */ insert into `user`(`id`,`name`,`gender`,`age`,`flag`) values (1,'allen',1,20,1),(2,'alice',2,18,1),(3,'bob',1,21,1),(4,'dave',1,25,1),(5,'eve',2,20,1),(6,'joy',1,21,1),(7,'june',1,23,1),(8,'linda',2,22,1),(9,'lisa',2,22,1),(10,'liz',2,23,1);
然後新建PHP檔案。pdo.php
<?php $db = array( 'host' => '127.0.0.1', //設定伺服器地址 'port' => '3306', //設埠 'dbname' => 'test', //設定資料庫名 'username' => 'root', //設定賬號 'password' => 'yangji0321', //設定密碼 'charset' => 'utf8', //設定編碼格式 'dsn' => 'mysql:host=127.0.0.1;dbname=test;port=3306;charset=utf8', //這裡不知道為什麼,也需要這樣再寫一遍。 ); //連線 $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //預設是PDO::ERRMODE_SILENT, 0, (忽略錯誤模式) PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // 預設是PDO::FETCH_BOTH, 4 ); try{ $pdo = new PDO($db['dsn'], $db['username'], $db['password'], $options); }catch(PDOException $e){ die('資料庫連線失敗:' . $e->getMessage()); } //或者更通用的設定屬性方式: //$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //設定異常處理方式 //$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); //設定預設關聯索引遍歷 echo '<pre/>'; //1 查詢 //1)使用query $stmt = $pdo->query('select * from user limit 2'); //返回一個PDOStatement物件 //$row = $stmt->fetch(); //從結果集中獲取下一行,用於while迴圈 $rows = $stmt->fetchAll(); //獲取所有 $row_count = $stmt->rowCount(); //記錄數,2 print_r($rows); echo '<br>'; //2)使用prepare 推薦! $stmt = $pdo->prepare("select * from user where name = ? and age = ? "); $stmt->bindValue(1,'allen'); $stmt->bindValue(2,20); $stmt->execute(); //執行一條預處理語句 .成功時返回 TRUE, 失敗時返回 FALSE $rows = $stmt->fetchAll(); $row_count = $stmt->rowCount(); //記錄數,2 print_r($rows); print_r($row_count); echo '<br>'; //2 新增、更新、刪除 //A.1)普通操作 //$count = $pdo->exec("insert into user(name,gender,age)values('test',2,23)"); //返回受影響的行數 //echo $pdo->lastInsertId(); //$count = $pdo->exec("update user set name='test2' where id = 15"); //返回受影響的行數 //$count = $pdo->exec("delete from user where id = 15"); //返回受影響的行數 //A.2)使用prepare 推薦! $stmt = $pdo->prepare("insert into user(name,gender,age)values(?,?,?)"); $stmt->bindValue(1, 'test'); $stmt->bindValue(2, 2); $stmt->bindValue(3, 23); $stmt->execute(); $count = $stmt->rowCount();//受影響行數 echo 'prepare方法影響行數:'.$count; echo '<br>'; //A.3)使用prepare 批量新增 $stmt = $pdo->prepare("insert into user(name,gender,age)values(?,?,?)"); $stmt->bindParam(1, $name); $stmt->bindParam(2, $gender); $stmt->bindParam(3, $age); $data = array( array('t1', 1, 22), array('t2', 2, 23), ); foreach ($data as $vo){ list($name, $gender, $age) = $vo; $stmt->execute(); } //B)更新操作 echo '<br>'; $stmt = $pdo->prepare("UPDATE `user` SET `age`=? WHERE (`name`= ? )"); $stmt->bindValue(1, '20'); $stmt->bindValue(2, 'allen'); $num = $stmt->execute(); $count = $stmt->rowCount();//受影響行數 echo '更新操作影響行數:'.$count; //刪除操作 $stmt = $pdo->prepare("DELETE FROM `user` WHERE (`name`= ? )"); $stmt->bindValue(1, 't1'); $num = $stmt->execute(); $count = $stmt->rowCount();//受影響行數 echo '刪除操作影響行數:'.$count; # 【示例5:統計資料】:統計company表有多少條資料 echo '<br>'; $num = $pdo->query("select count(*) from user"); $count = $num->fetchColumn(); echo '共有資料:【'.$count.'】條'; ?> pdo::query()方法 當執行返回結果集的select查詢時,或者所影響的行數無關緊要時,應當使用pdo物件中的query()方法. 如果該方法成功執行指定的查詢,則返回一個PDOStatement物件. 如果使用了query()方法,並想了解獲取資料行總數,可以使用PDOStatement物件中的rowCount()方法獲取. pdo::exec()方法 當執行insert,update,delete沒有結果集的查詢時,使用pdo物件中的exec()方法去執行. 該方法成功執行時,將返回受影響的行數.注意,該方法不能用於select查詢. PDO事務: $pdo->beginTransaction();//開啟事務處理 try{ //PDO預處理以及執行語句... $pdo->commit();//提交事務 }catch(PDOException $e){ $pdo->rollBack();//事務回滾 //相關錯誤處理 throw $e; }
程式能很好的執行,結果如下:
Array ( [0] => Array ( [id] => 1 [name] => allen [gender] => 1 [age] => 20 [flag] => 1 ) [1] => Array ( [id] => 2 [name] => alice [gender] => 2 [age] => 18 [flag] => 1 ) ) Array ( [0] => Array ( [id] => 1 [name] => allen [gender] => 1 [age] => 20 [flag] => 1 ) ) 1prepare方法影響行數:1 更新操作影響行數:0刪除操作影響行數:1 共有資料:【25】條 pdo::query()方法 當執行返回結果集的select查詢時,或者所影響的行數無關緊要時,應當使用pdo物件中的query()方法. 如果該方法成功執行指定的查詢,則返回一個PDOStatement物件. 如果使用了query()方法,並想了解獲取資料行總數,可以使用PDOStatement物件中的rowCount()方法獲取. pdo::exec()方法 當執行insert,update,delete沒有結果集的查詢時,使用pdo物件中的exec()方法去執行. 該方法成功執行時,將返回受影響的行數.注意,該方法不能用於select查詢. PDO事務: $pdo->beginTransaction();//開啟事務處理 try{ //PDO預處理以及執行語句... $pdo->commit();//提交事務 }catch(PDOException $e){ $pdo->rollBack();//事務回滾 //相關錯誤處理 throw $e; }
參考文獻:
http://www.cnblogs.com/52fhy/p/5352304.html
http://blog.csdn.net/qq_34341290/article/details/52964215
http://www.youhutong.com/index.php/article/index/143.html
http://www.cnblogs.com/lqcdsns/p/6724185.html?utm_source=itdadao&utm_medium=referral
http://www.cnblogs.com/CraryPrimitiveMan/p/4385034.html
https://segmentfault.com/q/1010000005107198