ci框架 查询构造器类

$this->db->get()

该方法执行 SELECT 语句并返回查询结果,可以得到一个表的所有数据:

$query = $this->db->get('mytable');  // Produces: SELECT * FROM mytable

第二和第三个参数用于设置 LIMIT 子句:

$query = $this->db->get('mytable', 10, 20);

// Executes: SELECT * FROM mytable LIMIT 20, 10
// (in MySQL. Other databases have slightly different syntax)

你应该已经注意到了,上面的方法的结果都赋值给了一个 $query 变量,通过这个变量, 我们可以得到查询的结果:

$query = $this->db->get('mytable');

foreach ($query->result() as $row)
{
    echo $row->title;
}

$this->db->select()

该方法用于编写查询语句中的 SELECT 子句:

$this->db->select('title, content, date');
$query = $this->db->get('mytable');

// Executes: SELECT title, content, date FROM mytable

注解

如果你要查询表的所有列,可以不用写这个函数,CodeIgniter 会自动查询所有列(SELECT *)。

$this->db->select() 方法的第二个参数可选,如果设置为 FALSE,CodeIgniter 将不保护你的 表名和字段名,这在当你编写复合查询语句时很有用,不会破坏你编写的语句。

$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
$query = $this->db->get('mytable');

链式方法

通过将多个方法连接在一起,链式方法可以大大的简化你的语法。感受一下这个例子:

$query = $this->db->select('title')
        ->where('id', $id)
        ->limit(10, 20)
        ->get('mytable');

$this->db->delete()

该方法生成 DELETE 语句并执行。

$this->db->delete('mytable', array('id' => $id));  // Produces: // DELETE FROM mytable  // WHERE id = $id

第一个参数为表名,第二个参数为 WHERE 条件。你也可以不用第二个参数, 使用 where() 或者 or_where() 函数来替代它:

$this->db->where('id', $id);
$this->db->delete('mytable');

// Produces:
// DELETE FROM mytable
// WHERE id = $id

如果你想要从多个表中删除数据,你也可以将由多个表名构成的数组传给 delete() 方法。

$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);

$this->db->delete()

该方法生成 DELETE 语句并执行。

$this->db->delete('mytable', array('id' => $id));  // Produces: // DELETE FROM mytable  // WHERE id = $id

第一个参数为表名,第二个参数为 WHERE 条件。你也可以不用第二个参数, 使用 where() 或者 or_where() 函数来替代它:

$this->db->where('id', $id);
$this->db->delete('mytable');

// Produces:
// DELETE FROM mytable
// WHERE id = $id

如果你想要从多个表中删除数据,你也可以将由多个表名构成的数组传给 delete() 方法。

$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);

$this->db->insert()

该方法根据你提供的数据生成一条 INSERT 语句并执行,它的参数是一个**数组** 或一个**对象**,下面是使用数组的例子:

$data = array(
    'title' => 'My title',
    'name' => 'My Name',
    'date' => 'My date'
);

$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

第一个参数为要插入的表名,第二个参数为要插入的数据,是个关联数组。

下面是使用对象的例子:

/*
class Myclass {
    public $title = 'My Title';
    public $content = 'My Content';
    public $date = 'My Date';
}
*/

$object = new Myclass;
$this->db->insert('mytable', $object);
原文地址:https://www.cnblogs.com/songyanan/p/8401021.html