codeigniter数据库操作笔记

数据库的运算并不是在控制类中进行的,而是在数据模型中,这样他们就可以在后面很容易地被反复使用。数据模型就是对你的数据库或其他数据存储方式进行取回、插入和更新的地方,它们的功能是展示你的数据(They represent your data)。

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);
 
时间: 2024-08-25 04:41:56

codeigniter数据库操作笔记的相关文章

018.CI4框架CodeIgniter数据库操作之:Delete删除一条数据

01. 在Model中写数据库操作语句,代码如下: <?php namespace App\Models\System; use CodeIgniter\Model; class User_model extends Model { var $Db; function __construct() { parent::__construct(); //创建数据库连接 $this->Db = \Config\Database::connect(); } function deletedata()

017.CI4框架CodeIgniter数据库操作之:Updata更新修改一条数据

01. 在Model中写入数据库操作的代码如下: <?php namespace App\Models\System; use CodeIgniter\Model; class User_model extends Model { var $Db; function __construct() { parent::__construct(); //创建数据库连接 $this->Db = \Config\Database::connect(); } function updatadata() {

015.CI4框架CodeIgniter数据库操作之:带参数查询数

01.我们在Models中写数据库的操作.具体的查询代码如下: <?php namespace App\Models\System; use CodeIgniter\Model; class User_model extends Model { var $Db; function __construct() { parent::__construct(); //创建数据库连接 $this->Db = \Config\Database::connect(); } function getdata

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

016.CI4框架CodeIgniter数据库操作之:插入一条数据

01.在Model中,写入插入的语句 <?php namespace App\Models\System; use CodeIgniter\Model; class User_model extends Model { var $Db; function __construct() { parent::__construct(); //创建数据库连接 $this->Db = \Config\Database::connect(); } function insertdata() { //带参数

013.CI4框架CodeIgniter数据库操作之:查询数据库,并让数据以数组的方式返回查询结果

01. 我们在CI4框架中的Model文件夹新建一个User_model.php的文件,使用的是getResultArray,表示并让数据以数组的方式返回查询结果,代码如下: <?php namespace App\Models\System; use CodeIgniter\Model; class User_model extends Model { var $Db; function __construct() { parent::__construct(); //创建数据库连接 $thi

CodeIgniter学习笔记(七)&mdash;&mdash;CI中的数据库操作

CI数据库配置文件是/application/config/database.php // 可以创建多个数据库连接配置,通过$active_group选择使用哪个数据库连接 $active_group = 'default'; // 配置是否加载查询构建类,默认为TRUE,通常保持默认值 $query_builder = TRUE; // 数据库连接配置,可以有多个连接配置,索引需要区分开 $db['default'] = array( 'dsn' => '', 'hostname' => '

CodeIgniter框架——访问方式 URI 分配变量 数据库操作

1.访问方式: CodeIgniter 的访问URL使用的是pathinfo,入口文件/控制器/方法(/参数列表) eg:localhost/index.php/welcome/index/id 第一段表示调用控制器类. 第二段表示调用类中的函数或方法. 第三及更多的段表示的是传递给控制器的参数,如 ID 或其它各种变量. 2.URI参数获取: 控制器端代码 1 public function getUri($id,$name,$year) 2 { 3 echo "id--->"

Flas-SQLAchemy数据库操作使用学习笔记

Flas-SQLAchemy数据库操作使用学习笔记 1.为你的Flask应用加载Flask-SqlAlchemy扩展 Code example: 1.1from flask import Flask f rom flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(ap