Usage examples of php pdo class library, examples of getting started with php pdo module

WBOY
Release: 2016-07-25 08:51:45
Original
1007 people have browsed it
  1. $dbh = new PDO('mysql:host=localhost;dbname=access_control', 'root', '');
  2. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  3. $dbh->exec('set names utf8');
  4. /*添加*/
  5. //$sql = "INSERT INTO `user` SET `login`=:login AND `password`=:password";
  6. $sql = "INSERT INTO `user` (`login` ,`password`)VALUES (:login, :password)"; $stmt = $dbh->prepare($sql); $stmt->execute(array(':login'=>'kevin2',':password'=>''));
  7. echo $dbh->lastinsertid();
  8. /*修改*/
  9. $sql = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId";
  10. $stmt = $dbh->prepare($sql);
  11. $stmt->execute(array(':userId'=>'7', ':password'=>'4607e782c4d86fd5364d7e4508bb10d9'));
  12. echo $stmt->rowCount();
  13. /*删除*/
  14. $sql = "DELETE FROM `user` WHERE `login` LIKE 'kevin_'"; //kevin%
  15. $stmt = $dbh->prepare($sql);
  16. $stmt->execute();
  17. echo $stmt->rowCount();
  18. /*查询*/
  19. $login = 'kevin%';
  20. $sql = "SELECT * FROM `user` WHERE `login` LIKE :login";
  21. $stmt = $dbh->prepare($sql);
  22. $stmt->execute(array(':login'=>$login));
  23. while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
  24. print_r($row);
  25. }
  26. print_r( $stmt->fetchAll(PDO::FETCH_ASSOC));
  27. ?>
复制代码

1、建立连接

  1. $dbh=newPDO('mysql:host=localhost;port=3306; dbname=test',$user,$pass,array(
  2. PDO::ATTR_PERSISTENT=>true
  3. ));
  4. ?>
复制代码

持久性链接PDO::ATTR_PERSISTENT=>true

2. 捕捉错误

  1. try{
  2. $dbh=newPDO('mysql:host=localhost;dbname=test',$user,$pass);
  3. $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  4. $dbh->exec("SET CHARACTER SET utf8");
  5. $dbh=null; //断开连接
  6. }catch(PDOException$e){
  7. print"Error!:".$e->getMessage()."
    ";
  8. die();
  9. }
  10. ?>
复制代码

3. 事务

  1. try{

  2. $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  3. $dbh->beginTransaction();//开启事务
  4. $dbh->exec("insertintostaff(id,first,last)values(23,'Joe','Bloggs')");
  5. $dbh->exec("insertintosalarychange(id,amount,changedate)
  6. values(23,50000,NOW())");
  7. $dbh->commit();//提交事务

  8. }catch(Exception$e){

  9. $dbh->rollBack();//错误回滚
  10. echo"Failed:".$e->getMessage();
  11. }
  12. ?>

复制代码

4. 错误处理 a. 静默模式(默认模式)

  1. try{
  2. $dbh = new PDO($dsn, $user, $password);
  3. $sql = 'Select * from city where CountryCode =:country';
  4. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
  5. $stmt = $dbh->prepare($sql);
  6. $stmt->bindParam(':country', $country, PDO::PARAM_STR);
  7. $stmt->execute();
  8. while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  9. print $row['Name'] . "/t";
  10. }
  11. } // if there is a problem we can handle it here
  12. catch (PDOException $e) {
  13. echo 'PDO Exception Caught. ';
  14. echo 'Error with the database:
    ';
  15. echo 'SQL Query: ', $sql;
  16. echo 'Error: ' . $e->getMessage();
  17. }
  18. ?>
复制代码

1. 使用 query()

  1. $dbh->query($sql); 当$sql 中变量可以用$dbh->quote($params); //转义字符串的数据

  2. $sql = 'Select * from city where CountryCode ='.$dbh->quote($country);

  3. foreach ($dbh->query($sql) as $row) {
  4. print $row['Name'] . "/t";
  5. print $row['CountryCode'] . "/t";
  6. print $row['Population'] . "/n";
  7. }
  8. ?>

复制代码

2. Use prepare, bindParam and execute [recommended, but can also be used to add, modify, and delete]

  1. $dbh->prepare($sql); generates a PDOStatement object
  2. PDOStatement->bindParam()
  3. PDOStatement->execute();//You can put it here The corresponding bound variables
  4. ?>
Copy code

3. Transaction

  1. try {
  2. $dbh = new PDO('mysql:host=localhost;dbname=test', 'root', '');
  3. $dbh->query('set names utf8;');
  4. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  5. $dbh->beginTransaction();
  6. $dbh->exec("Insert INTO `test`. `table` (`name` ,`age`)VALUES ('mick', 22);");
  7. $dbh->exec("Insert INTO `test`.`table` (`name` ,`age` )VALUES ('lily', 29);");
  8. $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('susan', 21);" );
  9. $dbh->commit();
  10. } catch (Exception $e) {
  11. $dbh->rollBack();
  12. echo "Failed: " . $e->getMessage();
  13. }
  14. ?>
Copy code

Common PDO methods: PDO::query() is mainly used for operations that return record results (PDOStatement), especially select operations.

PDO::exec() is mainly for operations that do not return a result set. Such as insert, update and other operations. Returns the number of affected rows. PDO::lastInsertId() returns the last ID of the last insertion operation, but please note: if you use insert into tb(col1,col2) values(v1,v2),(v11,v22).. to insert multiple records at one time , lastinsertid() returns only the ID of the first (v1, v2) insert, not the record ID of the last record inserted. PDOStatement::fetch() is used to obtain a record. Use while to traverse. PDOStatement::fetchAll() fetches all records into one. PDOStatement::fetchcolumn([int column_indexnum]) is used to directly access the column. The parameter column_indexnum is the index value of the column in the row starting from 0. However, this method can only obtain one column of the same row at a time. As long as it is executed once, it will jump. Go to the next line. Therefore, it is easier to use when directly accessing a certain column, but it is not useful when traversing multiple columns. PDOStatement::rowcount() is suitable for obtaining the number of records when using the query("select...") method. It can also be used in preprocessing. $stmt->rowcount(); PDOStatement::columncount() is suitable for obtaining the number of columns in a record when using the query("select...") method.

Note: 1. Choose fetch or fetchall? When the record set is small, using fetchall is efficient and reduces the number of retrieval times from the database. However, for large result sets, using fetchall brings a lot of burden to the system. The amount of data the database needs to transmit to the web front-end is too large and inefficient. 2. fetch() or fetchall() has several parameters:

mixed pdostatement::fetch([int fetch_style [,int cursor_orientation [,int cursor_offset]]]) array pdostatement::fetchAll(int fetch_style)

fetch_style parameters:

$row=$rs->fetchAll(PDO::FETCH_BOTH); FETCH_BOTH is the default, can be omitted, and returns the association and index. $row=$rs->fetchAll(PDO::FETCH_ASSOC); The FETCH_ASSOC parameter determines that only associative arrays are returned. $row=$rs->fetchAll(PDO::FETCH_NUM); returns index array $row=$rs->fetchAll(PDO::FETCH_OBJ); If fetch() returns an object, if fetchall() returns a two-dimensional array composed of objects


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!