php_pdo详解

7 篇文章 0 订阅
7 篇文章 0 订阅

PDO 类

PDO {
     //创建一个表示数据库连接的 PDO 实例
    __construct ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
    //启动一个事务
    bool beginTransaction ( void )
    //提交一个事务
    bool commit ( void )
    //获取跟数据库句柄上一次操作的错误码
    mixed errorCode ( void )
    //获取跟数据库句柄上一次操作的错误信息
    public array errorInfo ( void )
    //执行一条 SQL 语句,并返回受影响的行数
    int exec ( string $statement )
    //取回一个数据库连接的属性
    //[getAttribute详解](http://www.runoob.com/php/pdo-getattribute.html)
    mixed getAttribute ( int $attribute )
    //返回一个可用驱动的数组
    static array getAvailableDrivers ( void )
    //检查是否在一个事务内
    bool inTransaction ( void )
    //返回最后插入行的ID或序列值
    string lastInsertId ([ string $name = NULL ] )
    //准备要执行的SQL语句并返回一个 PDOStatement 对象
    public PDOStatement prepare ( string $statement [, array $driver_options = array() ] )
    //执行 SQL 语句,返回PDOStatement对象,可以理解为结果集
    public PDOStatement query ( string $statement )
    //为SQL语句中的字符串添加引号
    public string quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )
    //回滚一个事务
    bool rollBack ( void )
    //设置属性
    //[setAttribute 详解](http://www.runoob.com/php/pdo-setattribute.html)
    bool setAttribute ( int $attribute , mixed $value )
}

实例:

<?php
//[pdo初始化传值有三种方式,其他两种自己写配置文件或在php.ini中配置,详细看php.net](http://php.net/manual/zh/pdo.construct.php)
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
$db->exec("set names utf8");
//注意下面三种方式区别,默认索引数组和关联数组均有
$res = $db->query('SELECT * FROM `mytable` WHERE id = 1');
$result = $res->fetchAll();
$res = $db->query('SELECT * FROM `mytable` WHERE id = 1', PDO::FETCH_NUM);
$result = $res->fetchAll();
$res = $db->query('SELECT * FROM `mytable` WHERE id = 1', PDO::FETCH_ASSOC);
//[fetchAll详解](http://php.net/manual/zh/pdostatement.fetchall.php)
//不仅可以在query中指定返回结果集形式,也可以在fetchAll中指定返回形式
//fetchAll还可以将结果集传给指定类和方法,还可对结果集分组、取唯一值等
$result = $res->fetchAll();
$result = $res->fetchAll(PDO::FETCH_ASSOC);
$result = $res->fetchAll(PDO::FETCH_COLUMN);
$result = $res->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE);
//释放资源,pdo中没有像mysql_close这样的方法,需要手动释放
$db = null;
$res = null;
?>

query()的快捷操作方式:

<?php
    function getFruit($conn) {
        $sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
        //省掉了fetchall操作,直接得到结果
        foreach ($conn->query($sql) as $row) {
            print $row['name'] . "\t";
            print $row['color'] . "\t";
            print $row['calories'] . "\n";
        }
    }
?>
$pdo->exec("set names utf8");
$sql_link = "select name, url from link where passed = 1";
$res_link = $pdo->query($sql_link);
while ($row_link = $res_link->fetch(PDO::FETCH_ASSOC)) {
    $name = $row_link['name'];
    $url = $row_link['url'];
}

exec()使用:

<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
$db->exec("set names utf8");
/*  删除 FRUIT 数据表中满足条件的所有行 */
$count = $db->exec("DELETE FROM fruit WHERE colour = 'red'");

/* 返回被删除的行数 */
print("Deleted $count rows.\n");
?>

注意:对于数据库的查询操作的执行最好用query(),而对于数据库的增删改操作最好用exec()方法!

PDOStatement 类

PDOStatement implements Traversable {
    /* 属性 */
    //所用的查询字符串
    readonly string $queryString;
    /* 方法 */
    //绑定一列到一个 PHP 变量
    bool bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] )
    // 绑定一个参数到指定的变量名
    bool bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
    //把一个值绑定到一个参数
    bool bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )
    //关闭游标,使语句能再次被执行。
    bool closeCursor ( void )
    //返回结果集中的列数
    int columnCount ( void )
    //打印一条 SQL 预处理命令
    bool debugDumpParams ( void )
    //获取跟上一次语句句柄操作相关的 SQLSTATE
    string errorCode ( void )
    // 获取跟上一次语句句柄操作相关的扩展错误信息
    array errorInfo ( void )
    //执行一条预处理语句
    bool execute ([ array $input_parameters ] )
    //从结果集中获取下一行
    mixed fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
    //返回一个包含结果集中所有行的数组
    array fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )
    //从结果集中的下一行返回单独的一列。
    string fetchColumn ([ int $column_number = 0 ] )
    //获取下一行并作为一个对象返回。
    mixed fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )
    //检索一个语句属性
    mixed getAttribute ( int $attribute )
    // 返回结果集中一列的元数据
    array getColumnMeta ( int $column )
    //在一个多行集语句句柄中推进到下一个行集
    bool nextRowset ( void )
    //返回受上一个 SQL 语句影响的行数
    int rowCount ( void )
    //设置一个语句属性
    bool setAttribute ( int $attribute , mixed $value )
    //为语句设置默认的获取模式。
    bool setFetchMode ( int $mode )
}

PDOException 异常类

PDOException extends RuntimeException {
    /* 属性 */
    //获取跟上一次语句句柄操作相关的扩展错误信息
    public array $errorInfo ;
    //文本错误信息。
    protected string $message ;
    //SQLSTATE 错误码
    protected string $code ;
    /* 继承的方法 */
    //获取异常消息内容
    final public string Exception::getMessage ( void )
    //返回异常链中的前一个异常,否则返回NULL。
    final public Exception Exception::getPrevious ( void )
    //获取异常代码
    final public int Exception::getCode ( void )
    //获取发生异常的程序文件名称
    final public string Exception::getFile ( void )
    //获取发生异常的代码在文件中的行号
    final public int Exception::getLine ( void )
    // 获取异常追踪信息
    final public array Exception::getTrace ( void )
    //获取字符串类型的异常追踪信息
    final public string Exception::getTraceAsString ( void )
    //将异常对象转换为字符串
    public string Exception::__toString ( void )
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值