<?php //预处理的查询操作 // //1.连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=wd2018','root','root'); //2.准备SQL语句 $sql = "SELECT name,email FROM user WHERE user_id < :user_id"; //3.创建预处理对象:把当前的SQL语句抽象成一个对象 $stmt = $pdo->prepare($sql); //4.参数绑定 // $user_id =5; // $stmt->bindParam(':user_id',$user_id,PDO::PARAM_INT); // $stmt->bindValue(':user_id',5,PDO::PARAM_INT); //5.执行查询 $stmt -> execute(['user_id'=>5]); $stmt -> setFetchMode(PDO::FETCH_ASSOC); //6.解决结果集 // $row = $stmt->fatch();//获取到一条数据,自动下移指针 // $row = $stmt->fatch(); // $row = $stmt->fatch(); // $row = $stmt->fatch(); // while ($row = $stmt->fatch(PDO::FETCH_ASSOC)){//循环查询关联键值 // echo '<pre>'.print_r($row,true).'</pre>'; // } $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach($rows as $user) { echo $user['name'],'=>',$user['email'],'<br>'; } echo '<pre>'.print_r($row,true).'</pre>';
预处理操作链式操作
//1.连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=wd2018','root','root'); //2.创建预处理对象:把当前的SQL语句抽象成一个对象 $stmt = $pdo->prepare("SELECT name,email FROM user WHERE user_id < :user_id") -> execute(['user_id'=>5])//执行 ->fetchAll(PDO::FETCH_ASSOC);//获取结果集 //3.遍历结果集 foreach($rows as $user) { echo $user['name'],'=>',$user['email'],'<br>'; } echo '<pre>'.print_r($row,true).'</pre>';
//1.连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=wd2018','root','root'); //2.准备SQL语句 $sql = "SELECT name,email FROM user WHERE user_id < :user_id"; //3.创建预处理对象:把当前的SQL语句抽象成一个对象 $stmt = $pdo->prepare($sql); //4.参数绑定 $stmt -> execute($user_id =5); //5.将结果集中的列与变量进行绑定 $stmt->bindColumn('name',$name); $stmt->bindColumn('email',$email); while ($stmt->fetch()) { echo $name.' : '.$email.'<br>'; }
//1.连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=wd2018','root','root'); //2.准备SQL语句 (独立执行 不需要拼接) $sql1 = "SELECT name,salary FROM staff WHERE salary < :salary"; $sql2 = "SELECT name,salary FROM staff WHERE age < :age"; //3.创建预处理对象:把当前的SQL语句抽象成一个对象 $stmt1 = $pdo->prepare($sql1); $stmt2 = $pdo->prepare($sql2); //4.执行第一条查询 $stmt -> execute('salary'=>5000); //5.遍历第一个结果集 echo '<h2>工资小于5000的员工</h2>' $rows = $stmt1->fetchAll(PDO::FETCH_ASSOC); foreach($rows as $staff) { echo $user['name'],'=>',$staff['salary'],'<br>'; } //6.关闭第一个预处理对象 (重要) $stmt1->closeCursor(); //7.处理第二个结果集 $stmt2 -> execute('age'=>50); //5.遍历第二个结果集 echo '<h2>年龄大于50的员工</h2>' $rows = $stmt2->fetchAll(PDO::FETCH_ASSOC); foreach($rows as $staff) { echo $user['name'],'=>',$staff['age'],'<br>'; }