PDO对象的使用 (实现增删改查,输出错误等)

来源:互联网 发布:相马光子知乎 编辑:程序博客网 时间:2024/06/15 06:41
<?php//exec()增删改受影响的行数header("content-type:text/html;charset=utf-8");try{    $dsn='mysql:host=localhost;dbname=test';    $username='root';    $password='root';    $pdo=new PDO($dsn,$username,$password);    //exec():执行一条sql语句并返回其受影响的记录的行数    //exec()对于select没有作用 $sql=<<<SQL create table if not exists user( id int unsigned auto_increment key, username varchar(20) not null unique, password varchar(32) not null, email varchar(30) not null );SQL;//创建一个数据表,则没有受影响的行数,输出0    $res=$pdo->exec($sql);    echo "受影响记录的行数:".$res."<br>";//插入一条语句,输出1    $sql="insert user(username,password,email) values('king1',md5('king1'),'king1@qq.com')";    $res=$pdo->exec($sql);    echo  "受影响记录的行数:".$res."<br>";//lastInsertID()得到最后插入的id号     echo "最后插入的id号为:".$pdo->lastInsertID(); //更新一条语句(若更新后内容和更新前内容一样,则返回0行被影响)    $sql="update user set username='Tom' where id=1";    $res=$pdo->exec($sql);    echo "受影响记录的行数:".$res."<br>";//删除一条语句    $sql="delete from user where id=2";    $res=$pdo->exec($sql);    echo "受影响记录的行数:".$res."<br>";}catch(PDOException $e){    echo $e->getMessage();}?>

<?php//query执行查询语句header("content-type:text/html;charset=utf-8");try{    $dsn='mysql:host=localhost;dbname=test';    $username='root';    $password='root';    $pdo=new PDO($dsn,$username,$password);   $sql="select * from user where id=1";   //$pdo->query($sql)执行sql语句,返回PDOStatement对象    $stmt=$pdo->query($sql);    foreach($stmt as $value)    {        print_r($value);//得到关联加索引的数组        //echo $value['id'];        echo "<br>";    }}catch(PDOException $e){    echo $e->getMessage();}?>

<?php//用prepare(),execute()执行SQL查询语句header("content-type:text/html;charset=utf-8");try{    $dsn='mysql:host=localhost;dbname=test';    $username='root';    $password='root';    $pdo=new PDO($dsn,$username,$password);    $sql ="select * from user ";    //prepare():准备sql语句    $stmt=$pdo->prepare($sql);    //execute():执行预处理语句    $res=$stmt->execute();    //fetch():得到结果集中的一条记录    if($res)    {       // while($row=$stmt->fetch(PDO::FETCH_OBJ))//对象       // while($row=$stmt->fetch(PDO::FETCH_NUM))//索引数组       // while($row=$stmt->fetch(PDO::FETCH_ASSOC))//关联数组        while($row=$stmt->fetch(PDO::FETCH_BOTH))//关联加索引(默认)        {            print_r($row);            echo "<br>";        }    }    //fetchAll()返回所有查询结果,用法同上fetch()    $rows=$stmt->fetchAll();    print_r($rows);}catch(PDOException $e){    echo $e->getMessage();}?>

<?php//处理错误信息header("content-type:text/html;charset=utf-8");try{    $dsn='mysql:host=localhost;dbname=test';    $username='root';    $password='root';    $pdo=new PDO($dsn,$username,$password);    $sql="delete from user2 where name='king'";    $res=$pdo->exec($sql);    if($res==false)    {        echo $pdo->errorCode();//返回一个错误码SQLSTATE的值        echo "<br>";        print_r($pdo->errorInfo());//返回一个数组,[0]错误码[1]错误编号[2]错误内容信息    }}catch(PDOException $e){    echo $e->getMessage();}?>

原创粉丝点击