数据库抽象层 pdo


一 、 PDO的连接

  $host = "localhost";
    $dbname = "hejuntest";
    $username = "root";
    $pwd = "";
    $dsn = "mysql:host=$host;dbname=$dbname";
    $opt = array(PDO::ATTR_PERSISTENT => TRUE);  //持久链接
    try{
        $pdo = new PDO($dsn , $username , $pwd , $opt);
    }catch(PDOException $e){
        echo 'connect error~ ' . $e->get_Message(); 
    }

二 、PDO的增、删、改

    $sql = "update student set name='xiaoran' where id in(1,2) ";
    $affted_rows = $pdo->exec($sql);  //返回受影响的行数

三、 PDO的查

  • 使用fetch()

   

    $sql = "select * from student";
    $pdostatement = $pdo->query($sql);
    echo '<table>';
    while(list($id , $name , $age , $class) = $pdostatement->fetch(PDO::FETCH_NUM)){
        echo '<tr>';
        echo '<td>' . $id .'</td>';
        echo '<td>' . $name .'</td>';
        echo '<td>' . $age .'</td>';
        echo '<td>' . $class .'</td>';
        echo '</tr>';
    }
    echo '</table>';
  • 使用fetchAll()
    $sql = "select * from student";
    $pdostatement = $pdo->query($sql);
    $data = $pdostatement->fetchAll(PDO::FETCH_ASSOC);
    echo '<table>';
    foreach($data as $k => $v){
        echo '<tr>';
        echo '<td>' . $v['id'] .'</td>';
        echo '<td>' . $v['name'] .'</td>';
        echo '<td>' . $v['age'] .'</td>';
        echo '<td>' . $v['class'] .'</td>';
        echo '</tr>';
    }
    echo '</table>';

四、 PDO的预处理(支持采用预处理方式)

  • 指定名字绑定变量
    $sql = "insert into student (name,age,class) values (:name,:age,:class)";
    $pdostatement = $pdo->prepare($sql);
    
    $pdostatement->bindParam(":name" , $name);
    $pdostatement->bindParam(":age" , $age);
    $pdostatement->bindParam(":class" , $class);
    $name = "hejun";
    $age = 25;
    $class = 15;
    $pdostatement->execute();

    $name = "daxi";
    $age = 26;
    $class = 16;
    $pdostatement->execute();
  • ? 符号绑定变量
   $sql = "insert into student(name,age,class) values(?,?,?)";
    $pdostatement = $pdo->prepare($sql);
    
    $pdostatement->bindParam(1 , $name);
    $pdostatement->bindParam(2 , $age);
    $pdostatement->bindParam(3 , $class);

    $name = "hejun";
    $age = 25;
    $class = 15;
    $pdostatement->execute();

    $name = "daxi";
    $age = 26;
    $class = 16;
    $pdostatement->execute();
  • 省去绑定变量方法
    $sql = "insert into student(name,age,class) values(?,?,?)";
    $pdostatement = $pdo->prepare($sql);
    $pdostatement->execute(array("daxixi",20,11));

    echo $pdo->lastInsertId(); //如果有主键,得到最后一条插入的主键值

    echo '<br>' . $pdostatement->rowCount();//得到影响行数
原文地址:https://www.cnblogs.com/hejun695/p/5512690.html