Blogger Information
Blog 23
fans 0
comment 3
visits 15285
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PDO的基础学习操作--php线上班第九期
木易
Original
690 people have browsed it

1. pdo操作:连接、增删查改操作(手写)

  1. <?php
  2. //pdo连接
  3. //第一个参数是一个组合
  4. //mysql:标识
  5. //host=地址
  6. //dbname=库名
  7. //$pdo=new PDO('mysql:host:127.0.0.1;dbname=demo','root','root');
  8. //print_r($pdo);
  9. //数据库连接参数
  10. $db =[
  11. 'type'=>'mysql',
  12. 'host'=>'localhost',
  13. 'dbname'=>'demo',
  14. 'username'=>'root',
  15. 'password'=>'root',
  16. 'part'=> 3306
  17. ];
  18. $dsn ="{$db['type']}:host={$db['host']};dbname={$db['dbname']}";
  19. //$pdo =new PDO($dsn,$db['username'],$db['password']);
  20. //print_r($pdo);
  21. //报错时常用
  22. try{
  23. $pdo = new PDO($dsn,$db['username'],$db['password']);
  24. }catch(PDOException $e){
  25. die($e->getMessage());
  26. }

2. 练熟pdo操作

  1. <?php
  2. require __DIR__.'/demo1.php';
  3. //尽可能把参数变成可变的值,所以可以让自己更变名称
  4. //创建sql语句模板
  5. $sql ='INSERT INTO `demo1`SET `id`=:i';
  6. //预处理
  7. $stmt = $pdo ->prepare($sql);
  8. //stmt是什么?是预处理语句
  9. //要绑定语句,需要对预处理语句的参数进行设定
  10. $stmt ->bindParam('i',$id,PDO::PARAM_INT);
  11. $add =$stmt ->execute();
  12. if($add){
  13. $count =$stmt -> rowCount();
  14. if($count>0){
  15. echo'数据插入成功';
  16. }else{
  17. echo '数据插入失败';
  18. }
  19. }else{
  20. die(print_r($stmt-> errorInfo(),ture));
  21. }
  22. $pdo = null;
  23. print_r($pdo);
  1. <?php
  2. require __DIR__.'/demo1.php';
  3. $sql = 'UPDATE `demo1` SET `name`=:n,`id`=:i
  4. WHERE `state`=:s';
  5. $stmt = $pdo ->prepare($sql);
  6. $name='外公司';
  7. $id='3';
  8. $state='0';
  9. $stmt->bindParam('n',$name,PDO::PARAM_STR);
  10. $stmt->bindParam('i',$id,PDO::PARAM_STR);
  11. $stmt->bindParam('s',$state,PDO::PARAM_STR);
  12. $add = $stmt->execute();
  13. if($add){
  14. $count = $stmt-> rowCount();
  15. if($count>0){
  16. echo '数据插入成功';
  17. }else{
  18. echo'插入失败';
  19. }
  20. }else{
  21. die(print_r($stmt-> errorinfo(),true));
  22. }
  1. <?php
  2. require __DIR__.'/demo1.php';
  3. $sql ='SELECT * FROM `demo1`';
  4. $stmt =$pdo -> prepare($sql);
  5. $add= $stmt ->execute();
  6. if ($add){
  7. print_r($stmt->fetchAll());
  8. }else{
  9. die(print_r($stmt-> errorInfo(),true));
  10. }
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