Detailed explanation of php mysql connection method pdo usage

WBOY
Release: 2016-07-25 08:51:40
Original
1128 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,pdo事务

  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, you can also add, modify, 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 the code

3. PHP pdo transaction example

  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


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