codeIgniter数据库类使用教程

1.初始化数据库类
$this->load->database();

2.多结果标准查询(对象形式)
result();
例子:

$query = $this->db->query(‘SELECT name,title,email FROM my_table’);
foreach($query->result() as $row) {
//result()返回一个对象,如:$row->title
echo $row->title;
echo $row->name;
echo $row->email;
}

3.多结果标准查询(数组形式)

$query = $this->db->query(‘SELECT name,title,email FROM my_table’);
foreach($query->result_array() as $row) {
//result_array()返回一个带下标的数组,例如:$row[‘title’]
echo $row[‘title’];
echo $row[‘name’];
echo $row[’email’];
}

4.测试查询结果
使用num_rows()测试查询结果有无.

$query = $this->db->query(“Your Query”);
if($query->num_rows()>0) {
foreach($query->result() as $row) {
echo $row->name;
}
}

5.单结果标准查询(对象形式)

$query = $this->db->query(‘SELECT name FROM my_table LIMIT 1’);
$row = $query->row();
//row()函数返回一个对象.
echo $row->name;

6.单结果标准查询(数组形式)

$query = $this->db->query(‘SELECT name FROM my_table LIMIT 1’);
$row = $query->row_array();
//row_array()函数返回一个数组.
echo $row[‘name’];

7.标准插入(insert)

$sql = “INSERT INTO my_table (title,name) VALUES (“.$this->db->escape($title).”,”.$this->db->escape($name).”)”;
$this->db->query($sql);
echo $this->db->affected_rows();

8.快捷查询

$query = $this->db->get(‘table_name’);
//get()函数返回数据表中的所有记录.
foreach($query->result() as $row) {
echo $row->title;
}

9.快捷插入(insert)

$data = array(
‘title’ => $title,
‘name’ => $name,
‘date’ => $date
);
$this->db->insert(‘my_table’,$data);
//生成的SQL: INSERT INTO my_table (title,name,date) VALUES (‘{$title}’,'{$name}’,'{$date}’)

发表评论

返回顶部