PDO是什么?
来源:互联网 发布:排课表的软件 编辑:程序博客网 时间:2024/06/08 10:44
PDO一是PHP数据对象(PHP Data Object)的缩写。它被描述为“在PHP中访问数据库的轻量级,兼容性的接口”
PDO的好处:
- 免于SQL注入攻击。
- 通用,可以连接多种类型的数据库。
POD连接数据库
$dsn = 'mysql:dbname=blog;host=localhost';$user = 'root';$pwd = '';try{ $pdo = new PDO($dsn ,$user,$pwd);}catch( PDOException $e ){ var_dump($e->getMessage());}
PDO的基本操作: bool beginTransaction(void) //开启事务
bool commit(void) //提交事务
int exec (stirng $statement) //改的操作 返回受影响的行数
public PDOStatement query(string $statement) //用来执行查询的语句
public PDOStatement prepare (string $statment [, array $driver_options = array() ]) //sql语句的预处理,sql语句由它修饰后就会变成PDOStatement的对象 之后的操作就是用PDOStatement里面的方法进行处理
string lastInsertId ([string $name = null]) //得到上次插入语句的Id
PDOStatement的方法:
bool bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] ) //绑定参数
array fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] ) //得到所有的值
mixed fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] ) //得到某一行的数据
bool execute ([ array $input_parameters ] ) //执行SQL语句 只要是PDOStatement的对象就用这个执行
PDO的预处理方式:
$dsn = 'mysql:dbname=blog;host=localhost';$user = 'root' ;$pwd = '';try{ $pdo = new PDO($dsn,$user,$pwd);}catch(Exception $e){ var_dump($e->getMessage());}方式一:---------------------------------------------$sql = 'select mname , mcontent from message where id > :id';$pre = $pdo->prepare($sql);$pre->execute([':id' => 5]);var_dump($pre->fetchAll());方法二:$sql = 'select mname , mcontent from message where id > ?';$pre = $pdo->prepare($sql);$pre->execute([5]);var_dump($pre->fetchAll());--------------------------------------------方法三:$sql = 'select mname , mcontent from message where id > ?';$pre = $pdo->prepare($sql);$num = 5;$pre->bindParam(1,$num); //注意绑定的时候$num处不能为数字,$pre->execute(); //如果要处理数字的就传成变量var_dump($pre->fetchAll());---------------------------------------------方法四:$sql = 'select mname , mcontent from message where id > :id ';$pre = $pdo->prepare($sql);$num = 5;$pre->bindParam(':id',$num);$pre->execute();var_dump($pre->fetchAll());----------------------------------------------