CI框架中pdo的使用方法

来源:互联网 发布:中国移动杭州数据 编辑:程序博客网 时间:2024/06/08 09:49

1、配置
application/config文件夹下的database.php文件

[php] view plain copy
  1. $active_group = 'default';  
  2. $active_record = TRUE;  
  3. $db['default']['hostname'] = 'mysql:hostname=localhost;dbname=myproject';  
  4. $db['default']['username'] = 'myproject';  
  5. $db['default']['password'] = 'myproject';  
  6. $db['default']['database'] = '';  
  7. $db['default']['dbdriver'] = 'pdo';  
  8. $db['default']['dbprefix'] = '';  
  9. $db['default']['pconnect'] = TRUE;  
  10. $db['default']['db_debug'] = TRUE;  
  11. $db['default']['cache_on'] = FALSE;  
  12. $db['default']['cachedir'] = '';  
  13. $db['default']['char_set'] = 'utf8';  
  14. $db['default']['dbcollat'] = 'utf8_general_ci';  
  15. $db['default']['swap_pre'] = '';  
  16. $db['default']['autoinit'] = TRUE;  
  17. $db['default']['stricton'] = FALSE;  

2、使用方法

手动加载数据库

$this->load->database()

自动加载数据库

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

[php] view plain copy
  1. $autoload['libraries'] = array('database');  

select :

[php] view plain copy
  1. $sql = 'select * from aaa where id = :id';  
  2. $sql_array = array(  
  3.     ':id' => 1   
  4. );  
  5. $stmt = $this->db->conn_id->prepare($sql);  
  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
  1. (1)、$Count_num = count($arr_user);  
  2.   
  3. (2)、  
  4. $sql = 'select * from aaa where id = :id';  
  5. $sql_array = array(  
  6.     ':id' => 1   
  7. );  
  8. $stmt = $this->db->conn_id->prepare($sql);  
  9. $stmt->execute($sql_array);  
  10. $str_user = $stmt->fetch(PDO::FETCH_ASSOC);  
  11. $Count_num = $str_user[0];  


判断查询是否成功:

[php] view plain copy
  1. $stmt->execute($sql_array); //这句语句会返回true或者false,代表查询是否成功  



insert 、update、delete :

除了sql语句语法不同,查询的方法是一样的


[php] view plain copy
  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.   
  5. $sql_array = array(  
  6.     ':id' => 1   
  7. );  
  8. $stmt = $this->db->conn_id->prepare($sql);  
  9. $stmt->execute($sql_array);  

判断查询是否成功:

[php] view plain copy
  1. $stmt->rowCount();  
  2. if($stmt->rowCount()>0){  
  3.  //查询成功  
  4. }else{  
  5.  //查询失败  
  6. }  

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

[php] view plain copy
  1. pdo中的写法是 $stmt->lastInsertId();  


来源:http://blog.csdn.net/jalc2803/article/details/47258743