CI框架中pdo的使用方法

1、配置文件修改

application/config文件夹下的database.php文件

$db['default'] = array(
    'dsn'    => 'mysql:dbname=ci_ecshop;host=127.0.0.1',
    'username' => 'root',
    'password' => '',

    'dbdriver' => 'pdo',


2、查询操作

[php]   view plain  copy   在CODE上查看代码片 派生到我的代码片
  1. $sql = 'select * from aaa where id = :id';  
  2. $sql_array = array(  
  3.     ':id' => 1   
  4. );  
  5. $stmt = <span style="color:#FF0000;">$this->db->conn_id</span>->prepare($sql);//<span style="color:#FF6600;">$this->db->conn_id 是一个pdo对象</span>  
  6. $stmt->execute($sql_array);  
  7. $arr_user = $stmt->fetchAll(PDO::FETCH_ASSOC); //返回一个包含结果集中所有行的数组,相当于mysql中的result_array  
  8. $str_user = $stmt->fetch(PDO::FETCH_ASSOC); //从结果集中获取下一行,相当于mysql中的row_array  

判断查询是否成功:
[php]   view plain  copy   在CODE上查看代码片 派生到我的代码片
  1. $stmt->execute($sql_array); //这句语句会返回true或者false,代表查询是否成功  


3、insert 、update、delete  等操作
除了sql语句语法不同,查询的方法是一样的
[php]   view plain  copy   在CODE上查看代码片 派生到我的代码片
  1. $sql = "update aaa SET status = -1 WHERE id= :id";  
  2. $sql = "INSERT INTO aaa(`id`) VALUES ( :id)";  
  3. $sql = "delete from aaa where id= :id";  
  4. $sql_array = array(  
  5.     ':id' => 1   
  6. );  
  7. $stmt = $this->db->conn_id->prepare($sql);  
  8. $stmt->execute($sql_array);  

判断查询是否成功:

[php]   view plain  copy   在CODE上查看代码片 派生到我的代码片
  1. $stmt->rowCount();  
  2. if($stmt->rowCount()>0){  
  3.  //查询成功  
  4. }else{  
  5.  //查询失败  
  6. }  

4、另外,insert的时候,有时候需要返回insert_id

[php]   view plain  copy   在CODE上查看代码片 派生到我的代码片
  1. pdo中的写法是 $stmt->lastInsertId(); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值