Summary of Optimized Writing of Codeigniter Operational Database Tables
- 2021-06-29 10:25:31
- OfStack
codeigniter has been used for some time, 1 has not done anything to summarize.Now summarize some of the Codeigniter operation database table optimizations, although not complete, but can really help those who have just started CI.
Link Database
$this->load->database();// Manual connection to database
// Connect to multiple databases
$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);
query
// Parameter Binding Form
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
// Multi-Result Standard Query
$query = $this->db->query($sql); // custom
$query = $this->db->get('tablename'); // Convenient form, equivalent to :SELECT * FROM tablename
$query = $this->db->get('tablename', 10, 20); // Amount to : SELECT * FROM tablename LIMIT 20, 10
$query->result() // Object Form
$query->result_array() // Array Form
/*
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->email;
}
*/
$query->num_rows() // Total number of bars
$query->num_fields() // Number of fields
// Single Result Standard Query
$row = $query->row(); // Object Form
$row = $query->row_array(); // Array Form
/*
$row = $query->row_array();
echo $row['name'];
*/
insert
$data = array(
'title' => $title,
'name' => $name
);
$this->db->insert('tablename', $data); // Easy insertion
$this->db->insert_string('tablename', $data); // Easy insertion
$this->db->insert_id() // Newly inserted id
$this->db->affected_rows() // Number of rows affected (update,insert)
To update
$data = array(
'name' => $name,
'email' => $email
);
$where = "id = 1";
$this->db->update('tablename', $data);
$this->db->update_string('tablename', $data, $where);
delete
$array = array(
'name' => $name,
'title' => $title
);
$this->db->delete('tablename', $array);
// Produces:
// "DELETE FROM tablename WHERE name = '$name' AND title = "$title""
$this->db->truncate('tablename'); // Empty table
// Produce: TRUNCATE tablename
-----------------------------------------------------
( where )
-------
$array = array(
'name' => $name,
'title' => $title
);
$this->db->where($array);
// Produces: "WHERE name = '$name' AND title = "$title""
-----------------------------------------------------
$this->db->count_all('tablename'); // Total number of rows recorded in the table
-----------------------------------------------------
$query->free_result() // Release Resources