php CI数据库操作整理

本文详细介绍CodeIgniter框架下的数据库操作方法,包括查询、插入、更新、删除等基本操作及高级用法如事务处理、查询缓存等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php框架codeigniter数据库操作整理

1.

$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result() as $row)
{
    echo $row->title;
    echo $row->name;
    echo $row->email;
}
2.
foreach ($query->result_array() as $row)
{
    echo $row['title'];
    echo $row['name'];
    echo $row['email'];
}
3.
if ($query->num_rows() > 0)

 

4.
$query = $this->db->query('SELECT name FROM my_table LIMIT 1');
$row = $query->row();//$row = $query->row_array();
echo $row->name;

 

//你可以传递参数以便获得某一行的数据。比如我们要获得第 5 行的数据:
$row = $query->row_array(5);
//除此以外, 我们还可以使用下面的方法通过游标的方式获取记录:
$row = $query->first_row()
$row = $query->last_row()
$row = $query->next_row()
$row = $query->previous_row()

5.
$sql = "INSERT INTO mytable (title, name)
        VALUES (".$this->db->escape($title).", ".$this->db->escape($name).")";
$this->db->query($sql);//$query = $this->db->get('table_name');
echo $this->db->affected_rows();
6.
$data = array(
               'title' => $title,
               'name' => $name,
               'date' => $date
            );
$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}')
7.
$this->db->escape()
8.
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick')); //自动转义
9.
//该函数返回当前请求的字段数(列数):
$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_fields();
10.
$query = $this->db->query('SELECT title FROM my_table');
foreach ($query->result() as $row)
{
   echo $row->title;
}
$query->free_result(); // $query 将不再可用
$query2 = $this->db->query('SELECT name FROM some_table');
$row = $query2->row();
echo $row->name;
$query2->free_result(); // $query2 将不再可用
11.
$this->db->insert_id()
$this->db->affected_rows()
$this->db->count_all();
$this->db->platform()
$this->db->version()
$this->db->last_query();
$this->db->insert_string();
$this->db->update_string();
12.AR
$this->db->get();
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
$this->db->select('title, content, date');
$query = $this->db->get('mytable');
$this->db->select_max('age');//min,avg,sum
$query = $this->db->get('members');
If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are 'before', 'after' and 'both' (which is the default).
$this->db->like('title', 'match', 'before');
// Produces: WHERE title LIKE '&#xma;tch'
$this->db->like('title', 'match', 'after');
// Produces: WHERE title LIKE 'match%'
$this->db->like('title', 'match', 'both');
// Produces: WHERE title LIKE '&#xma;tch%'
$this->db->insert();
$this->db->update();
$this->db->delete();
$this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20);
$query = $this->db->get();
$this->db->start_cache();
$this->db->select('field1');
$this->db->stop_cache();
$this->db->get('tablename');
// Results in:
// SELECT `field1` FROM (`tablename`)
$this->db->select('field2');
$this->db->get('tablename');
// Results in:
// SELECT `field1`, `field2` FROM (`tablename`)
$this->db->flush_cache();
$this->db->select('field2');
$this->db->get('tablename');
// Results in:
// SELECT `field2` FROM (`tablename`)
13.事务
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();
You can run as many queries as you want between the start/complete functions and they will all be committed or rolled back based on success or failure of any given query.

Strict Mode
By default CodeIgniter runs all transactions in Strict Mode. When strict mode is enabled, if you are running multiple groups of transactions, if one group fails all groups will be rolled back. If strict mode is disabled, each group is treated independently, meaning a failure of one group will not affect any others.
Strict Mode can be disabled as follows:
$this->db->trans_strict(FALSE);
Managing Errors
If you have error reporting enabled in your config/database.php file you'll see a standard error message if the commit was unsuccessful. If debugging is turned off, you can manage your own errors like this:
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
    // generate an error... or use the log_message() function to log your error
}
Enabling Transactions
Transactions are enabled automatically the moment you use $this->db->trans_start(). If you would like to disable transactions you can do so using $this->db->trans_off():
$this->db->trans_off()
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->trans_complete();
When transactions are disabled, your queries will be auto-commited, just as they are when running queries without transactions.

14.$this->db->list_tables();
Returns an array containing the names of all the tables in the database you are currently connected to. Example:

返回一个正在连接的数据库中所有表名称的数组。例如:
$tables = $this->db->list_tables();//fields
foreach ($tables as $table)
{
   echo $table;
}
$this->db->table_exists();
Sometimes it's helpful to know whether a particular table exists before running an operation on it. Returns a boolean TRUE/FALSE. Usage example:

。当想了解系统运行前某个表格是否存在时就变得非常有用。返回一个布尔值:TRUE/FALSE。例子:
if ($this->db->table_exists('table_name'))//field
{
   // some code...
}
15.查询缓存
// Turn caching on
$this->db->cache_on();
$query = $this->db->query("SELECT * FROM mytable");
// Turn caching off for this one query
$this->db->cache_off();
$query = $this->db->query("SELECT * FROM members WHERE member_id = '$current_user'");
// Turn caching back on
$this->db->cache_on();
$query = $this->db->query("SELECT * FROM another_table");
$this->db->cache_delete('blog', 'comments');
$this->db->cache_delete_all()
16.dbutil(数据库工具类)
$this->load->dbutil()
$dbs = $this->dbutil->list_databases();
foreach($dbs as $db)
{
    echo $db;
}
if ($this->dbutil->optimize_table('table_name'))
{
    echo 'Success!';
}

if ($this->dbutil->repair_table('table_name'))
{
    echo 'Success!';
}
$result = $this->dbutil->optimize_database();
if ($result !== FALSE)
{
    print_r($result);
}
$this->load->dbutil();
$query = $this->db->query("SELECT * FROM mytable");
echo $this->dbutil->csv_from_result($query);
$this->load->dbutil();
$query = $this->db->query("SELECT * FROM mytable");
$config = array (
                  'root'    => 'root',
                  'element' => 'element',
                  'newline' => "/n",
                  'tab'    => "/t"
                );
echo $this->dbutil->xml_from_result($query, $config);
$backup =& $this->dbutil->backup();
// Load the file helper and write the file to your server
$this->load->helper('file');
write_file('/path/to/mybackup.gz', $backup);
// Load the download helper and send the file to your desktop
$this->load->helper('download');
force_download('mybackup.gz', $backup);

 转:http://blog.youkuaiyun.com/jianglei421/article/details/5812377

<think>好的,用户想了解CI框架的使用介绍和官方文档。首先,我需要确定用户提到的CI框架具体是哪一个,因为常见的CI框架有两个:CodeIgniter和持续集成(Continuous Integration)。不过,根据用户提供的引用内容,特别是引用[1]中的代码示例,明显是关于PHP的CodeIgniter框架,因为提到了继承CI_Model和数据库操作。所以接下来,我应该围绕CodeIgniter框架进行解答。 接下来,用户需要的是使用介绍或官方文档。我需要整理CodeIgniter的基本结构、配置方法、模型、视图、控制器的使用,以及如何获取官方文档的信息。根据引用[1],用户可能已经接触到模型层的编写,但可能需要更全面的指导。引用[2]提到了配置文件的base_url和index_page设置,这说明用户可能对配置部分也感兴趣。因此,我应该涵盖安装步骤、目录结构、控制器、模型、视图的创建,以及路由和配置的基本设置。 另外,用户提供的引用内容中提到了模型继承CI_Model,数据库操作使用$this->db->get()等方法,这些在回答中需要详细说明。同时,引用[2]中的配置示例需要解释清楚各个配置项的作用,比如base_url和index_page的意义,以及如何根据项目需求进行调整。 还需要注意用户可能遇到的常见问题,例如如何连接数据库、如何创建表单处理等,但根据当前问题,用户主要需要的是基本使用介绍和官方文档的指引。因此,回答需要结构清晰,分步骤介绍,并确保每个部分都有对应的代码示例,符合用户提供的引用中的代码格式,比如模型和配置的示例。 最后,生成的相关问题需要围绕用户可能进一步询问的方向,比如配置项详解、数据库操作进阶、URL路由设置等,这些都能帮助用户深入理解CI框架的使用。同时,确保引用标识正确添加到对应的引用内容后,如引用[1]和引用[2]的具体内容。</think>### CI框架使用介绍 CodeIgniter(简称CI)是轻量级PHP框架,采用MVC架构,以下为关键使用步骤: #### 1. 安装与配置 下载最新版本后解压到Web目录,核心目录结构: ``` application/ ├─ config/ # 配置文件 ├─ models/ # 数据模型 ├─ views/ # 视图模板 ├─ controllers/ # 控制器 system/ # 框架核心 ``` 配置示例(application/config/config.php): ```php $config['base_url'] = "http://localhost/ci_project/"; # 项目根路径[^2] $config['index_page'] = "index.php"; # 入口文件[^2] ``` #### 2. 创建控制器 在controllers目录新建文件: ```php class Welcome extends CI_Controller { public function index() { $this->load->view('welcome_message'); } } ``` #### 3. 创建模型(继承CI_Model) ```php class User_model extends CI_Model { public function get_users() { return $this->db->get('users')->result_array(); # 数据库查询示例[^1] } } ``` #### 4. 视图渲染 控制器中调用: ```php $data['users'] = $this->User_model->get_users(); $this->load->view('user_list', $data); ``` #### 5. 路由配置 routes.php设置访问路径: ```php $route['default_controller'] = 'welcome'; $route['admin'] = 'admin/dashboard'; # 自定义路由 ``` ### 官方文档资源 CodeIgniter官方文档地址:https://codeigniter.com/user_guide 文档包含: - 完整类库参考 - 数据库操作指南 - 安全规范 - 扩展开发方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值