PHP程序中使用PDO对象实现对数据库的增删改查操作的示例代码

PHP程序中使用PDO对象实现对数据库的增删改查操作(PHP+smarty)

dbconn.php

<?php

//------------------------使用PDO方式连接数据库文件-----------------------------------//

$dsn="mysql:host=localhost;dbname=xsphp";

$username="root";

$passwd="";



try{

    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET NAMES UTF8");

    $pdo= new PDO($dsn, $username, $passwd, $options);

}catch(Exception $e){

   echo $e->getMessage();

} 

demo.php

这是demo.php文件要包含的文件(数据库连接和其他一些初始化信息)

include "init.inc.php";

include "dbconn.php";

//pdo对象实现增加一条记录

    $sql1="insert into xs_user(username,passwd,sex,addtime)values(?,?,?,?)"; //1、写sql语句

    $stmt=$pdo->prepare($sql1);                                              //预处理

    

    $stmt->bindParam(1,$username);                                           //2.绑定参数

    $stmt->bindParam(2,$passwd);

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

    $stmt->bindParam(4, $addtime);

    

    $username ="红苹果";                                                       //3.准备要插入的数据

    $passwd = md5("123");

    $sex ="女";

    date_default_timezone_set('PRC');      //设置时区PRC东八区

    $addtime= date('Y:m:d H:i:s',time());  //time()获取时间戳

    $flag = $stmt->execute();              //返回值是sql语句是否正确,只要sql语句正确,那么返回值都是true。

    

//PDO对象实现删除一条记录

    $sql3 = "delete from xs_user where `username`= ?";

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

    $flag3 = $stmt->execute(array("bright001"));   //把where条件的参数放到一个数组array中

    echo $sql3;

   if($flag3){

     $data = $stmt->fetch();

     $smarty->assign("flag","ok");

   }else{

     $smarty->assign("flag","fail");

   }

    //PDO对象实现更改一条记录

    

    $sql4= "update xs_user set `passwd`=md5('123') where `username`=? and `sex`=?";

    echo $sql4;

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

    $username = "bright0010";

    $sex = "女";                        //一种是直接写在execute的参数array()带进去,一种是通过绑定参数法

    $stmt->bindParam(1, $username);

    $stmt->bindParam(2, $sex);

    $flag4 = $stmt->execute();          //execute()函数带一个数组,array('bright006','男')当查询的条件多个时,直接按序写在array数组里面即可
$res = $stmt->rowCount();
if($res>0){ $data = $stmt->fetch(); $smarty->assign("flag","ok"); }else{ $smarty->assign("flag","fail"); }

    //PDO对象实现查询记录

    $sql5="select * from xs_user where `sex`=?";      

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

    $sex="女";

    $stmt->bindParam(1,$sex);

    $stmt->execute();

    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);      //关联数组的形式

    $smarty->assign("data",$data);

   

最后显示到smarty模板即可

$smarty -> display("test.tpl");

 

你可能感兴趣的:(增删改查)