`
vtrtbb
  • 浏览: 358379 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

php CI数据库操作整理

    博客分类:
  • php
 
阅读更多

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.csdn.net/jianglei421/article/details/5812377

分享到:
评论

相关推荐

    CI .laravel,cake php框架合集

    【标题】"CI .laravel,cake php框架合集"所涵盖的是三个主流的PHP框架:CodeIgniter(CI)、Laravel和CakePHP。这些框架是开发者用来构建高效、可维护的Web应用的重要工具。 **CodeIgniter(CI)** CodeIgniter是一...

    ci中文手册

    CI提供了一套简单的Active Record查询接口,使数据库操作变得简单易懂。 **7. 库(Libraries)** CI预装了一些常用的库,如Email库、Session库等。你可以自定义库或扩展已有的库来实现特定功能。 **8. 辅助函数...

    基于PHP的企业门户网站(源码+数据库).zip

    1、创建company数据库,字符集:UTF-8 unicode,整理:uft8_general_ci。 2、在company数据库运行【SQL文件导入】文件夹中的company.sql文件,运行后,将自动创建出company数据库中的表。 3、在inc文件夹下db_config...

    三国霸业文字游戏PHP商业源码完整版

    进入数据库,点右上角的操作 下面的整理选gb2312_chinese_ci 4.点击IMPORT 选择数据库文件夹下sql 文件。导入下面的编码选GB2312 5.导入成功后,即可进入游戏 6.后台地址:xxx.xxxxx.xxx/admin.php 默认管理员账号 ...

    php100视频教程全部ppt(1-112)合集整理

    - **PHP常用工具和数据库常用工具**:列举了几款流行的PHP开发工具如Zend Studio、PHPedit、EditPlus2等,以及MySQL数据库管理工具如MySQL Administrator,这些工具可提高开发效率和数据库操作的便利性。...

    解决php写入数据库乱码的问题

    当使用phpMyAdmin创建数据库时,确保在“整理”(Collation)设置中选择“utf8_general_ci”。若手动执行SQL创建,可以使用以下语句: ```sql CREATE DATABASE `dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8...

    MYSQL数据库使用UTF-8中文编码乱码的解决办法

    在PHPMyAdmin中,可以将“整理”设置为“utf8_general_ci”。用SQL语句创建数据库,可以使用以下命令: ``` CREATE DATABASE `dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; ``` - 创建数据表时...

    PHP网页游戏三国源码

    3.进入数据库,点右上角的操作 下面的整理选gb2312_chinese_ci 4.点击IMPORT 选择数据库文件夹下sql 文件。导入下面的编码选GB2312 5.导入成功后,即可进入游戏 6.后台地址:xxx.xxxxx.xxx/admin.php 默认管理员账号 ...

    php三国霸业webgame

    3.进入数据库,点右上角的操作 下面的整理选gb2312_chinese_ci 4.点击IMPORT 选择数据库文件夹下sql 文件。导入下面的编码选GB2312 5.导入成功后,即可进入游戏 6.后台地址:xxx.xxxxx.xxx/admin.php 默认管理员...

    php面试题(完整版整理)

    包括日期操作、版本控制、模板引擎、缓存技术、网络通信、错误处理、正则表达式、JavaScript交互、session机制、SQL安全、HTTP状态码、PHP对象、Apache配置、文件包含、序列化、递归和MySQL数据库操作。这些内容覆盖...

    php网页三国霸业游戏

    3.进入数据库,点右上角的操作 下面的整理选gb2312_chinese_ci 4.点击IMPORT 选择数据库文件夹下sql 文件。导入下面的编码选GB2312 5.导入成功后,即可进入游戏 6.后台地址:xxx.xxxxx.xxx/admin.php 默认管理员账号 ...

    PHP的面试题集收集整理.doc

    【PHP面试题集收集整理】 面试题1:此题考察日期时间处理,PHP可以通过`date('Y-m-d H:i:s', strtotime('-1 day'))`获取前一天的特定格式时间。 面试题2:`echo()`、`print()`和`print_r()`都是PHP的输出函数。`...

    PHP电子商务源码

    程序介绍 开发:PHP+MYSQL 主机环境要求: ...1、创建一个数据库,建的时候选择“整理”方式为:utf-8 general ci 2、将base/install/db/db.sql导入数据库 3、修改网站下的config.inc.php,数据库链接信息修改。

    Excel数据导入Mysql数据库的实现代码

    整理选项可以选择gb2312_chinese_ci,这是针对中文字符的排序规则。 接下来,我们利用Navicat的导入向导功能来导入Excel数据。点击右上角的导入向导按钮,选择数据类型为Excel文件,然后指定Excel文件的路径和需要...

    基于PHP的狂盗小说采集.zip

    7. **持续集成/持续部署(CI/CD)**:为了确保代码质量与项目进度,可以采用Git进行版本控制,配合Jenkins、Travis CI等工具实现自动化测试和部署。 8. **合规性问题**:在进行网页数据采集时,需遵守相关法律法规,...

    整理的一些资料

    此外,文档可能还会涉及软件工程的最佳实践、版本控制(如Git)、项目管理工具(如JIRA)、持续集成/持续部署(CI/CD)等内容,这些都是现代IT开发中的重要组成部分。通过这份资料,无论是初学者还是有一定经验的...

    mysql乱码解决方法

    新建数据库时,确保在“整理”(Collation)栏选择`utf8_unicode_ci`,以确保所有新创建的表默认使用UTF-8。 8. **全面使用UTF-8**: 推荐在整个网站项目中统一使用UTF-8编码,包括网页、数据库、文件等,以避免因...

    DB2基本操作

    根据提供的文件内容,我们可以归纳出以下与DB2相关的知识点,主要涵盖了DB2的基本操作、数据库管理配置以及系统命令等。 ### DB2基本操作 #### 创建DB2实例 - **32位系统创建实例:** - 命令格式:`/usr/opt/db2_...

Global site tag (gtag.js) - Google Analytics