Blogger Information
Blog 42
fans 5
comment 0
visits 38613
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php class类 PDO连接数据,增删查改
张浩刚
Original
739 people have browsed it

1、数据库连接

  1. class Db{
  2. public $dns;
  3. public $user;
  4. public $password;
  5. public $pdo;
  6. function __construct($dns,$user,$password){
  7. $this->dns = $dns;
  8. $this->user = $user;
  9. $this->password = $password;
  10. //连接数据库
  11. $this->content();
  12. }
  13. function content(){
  14. $this->pdo = new PDO($this->dns,$this->user,$this->password);
  15. }
  16. function __destruct(){
  17. $this->pdo = null;
  18. echo '执行完毕,关闭连接';
  19. }
  20. }
  21. $db = new Db('mysql:host=locaohost;dbname=film', 'root', 'root');
  22. print_r($db->pdo); //结果为PDO Object ( ) ,连接数据库成功

2、查询

  1. $stmt = $db->pdo->prepare('SELECT * FROM `user` WHERE `id`>=:id');
  2. $stmt -> execute(['id'=>1]);
  3. $stmt -> setFetchMode(PDO::FETCH_ASSOC);
  4. while( $user = $stmt->fetch() ){
  5. print_r($user);
  6. }
  7. ===================
  8. print_r( $stmt->fetchAll() ); //或者全部调用

3、新增

  1. $stmt = $db->pdo->prepare('INSERT `user`(name,tel,password) VALUES(:name,:tel,:password)');
  2. $stmt -> execute(['name'=>张明朗, 'tel'=>18080809999, 'password'=>sha1(123456)]);

4、更改

  1. $stmt = $db->pdo->prepare('UPDATE `user` SET `name`=:name, `tel`=:tel WHERE `id`=:id');
  2. $stmt -> execute(['id'=>9,'name'=>'张明轩','tel'=>19980807777]);

5、删除

  1. $stmt = $db->pdo->prepare('DELECT FROM `user` WHERE `id`=:id ');
  2. $stmt->execute(['id'=12]);
Correcting teacher:查无此人查无此人

Correction status:qualified

Teacher's comments:完成的不错,继续加油。作业最好写点自己看法和总结。
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post