您的位置:首页 > 编程语言 > PHP开发

php学习笔记之PDO预处理

2016-06-11 23:27 603 查看
PDO预处理方法

prepare()// 用于执行查询SQL语句,返回PDOStatement对象

bindValue() //将值绑定到对应的一个参数,返回布尔值

bindParam()//将参数绑定到相应的查询占位符上,返回布尔值

bindColumn() //用来匹配列名和一个指定的变量名

execte() //执行一个准备好了的预处理语句,返回布尔值

rowCount() // 返回使用增删改查操作语句所影响的行总数

1.预处理语句

$sql="insert into   sdu(id ,name ,sex,age) values(?,?,?,?)";

$stmt=$pdo->prepare($sql);

(1)?号绑定方式

$stmt->bindValue(1,null);

$stmt->bindValue(2,'test55');

$stmt->bindValue(3,'w');

$stmt->bindValue(4,22);

(2)第二种绑定方式

$etmt->bindParam(1,$id);

$etmt->bindParam(2,$name);

$etmt->bindParam(3,$sex);

$etmt->bindParam(4,$age);

$id=null;

$name="test66";

$sex="m";

$age=33;

执行

$stmt->execute();

(3)第三种绑定方法直接在执行的时候添加

$stmt->execute(array(null,'test77','w',66));

2.

预处理语句

$sql="insert into   sdu(id ,name ,sex,age)

$stmt=$pdo->prepare($sql);

(1)?号绑定方式

$stmt->bindValue("id",null);

$stmt->bindValue("name",'test55');

$stmt->bindValue("sex",'w');

$stmt->bindValue("age",22);

(2)第二种绑定方式

$etmt->bindParam("id",$id);

$etmt->bindParam("name",$name);

$etmt->bindParam("sex",$sex);

$etmt->bindParam("age",$age);

$id=null;

$name="test66";

$sex="m";

$age=33;

执行

$stmt->execute();

(3)第三种绑定方法直接在执行的时候添加

$stmt->execute(array("id"=>null,"name"=>'test77',"sex"=》'w',"age"=>66));(利用数组)

3.预处理查询

<?php

//连接数据库

header('content-type:text/html;charset=utf-8');

$pdo=new PDO("mysql:host=127.0.0.1;dbname=test","root","");

$pdo->query('set names utf8');//设置字符集

//在这里构建分页查询

$sql = "select id,name,class  from user";

$stmt=$pdo->prepare($sql);

$stmt->execute();

$stmt->bindColumn('id',$id);

$stmt->bindColumn(2,$name);

$stmt->bindColumn(3,$class);

while ($row=$stmt->fetch()) {

    echo "{$id}.{$name}.{$class}";

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php