Database QuickStart Example code
The following section will briefly explain how to use the database. For more detailed information, please read the separate introduction page for each function.
Initializing the Database class
The following code loads and initializes the database class according to your database configuration:
$this->load->database();
Once loaded, you can use it anywhere like this:
Note: If all of your pages require the initialization of the database class, you can let it load automatically. See database connections.
Multi-result standard query (object form)
$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;
}
echo ‘Total Results: ‘ . $query->num_rows();
The result () function above returns an array of objects . Example: $row->title
Multi-result standard query (array form)
$query = $this->db->query(‘SELECT name, title, email FROM my_table‘);
foreach ($query->result_array() as $row)
{
echo $row[‘title‘];
echo $row[‘name‘];
echo $row[‘email‘];
}
The result_array () function above returns an array with the subscript. Example: $row [' title ']
Test Query Results
If your query may not return results, we recommend that you first use the num_rows () function to test:
$query = $this->db->query("YOUR QUERY");
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
}
Single-result standard query (object form)
$query = $this->db->query(‘SELECT name FROM my_table LIMIT 1‘);
$row = $query->row();
echo $row->name;
The row () function above returns an object . Example: $row->name
Single-result standard query (array form)
$query = $this->db->query(‘SELECT name FROM my_table LIMIT 1‘);
$row = $query->row_array();
echo $row[‘name‘];
The row_array () function above returns an array . Example: $row [' name ']
Standard insertion (INSERT)
$sql = "INSERT INTO mytable (title, name)
VALUES (".$this->db->escape($title).", ".$this->db->escape($name).")";
$this->db->query($sql);
echo $this->db->affected_rows();
Quick Query
The Quick query class provides us with a way to get data quickly:
$query = $this->db->get(‘table_name‘);
foreach ($query->result() as $row)
{
echo $row->title;
}
The get () function above returns all results in the data table. The shortcut query class provides shortcut functions for all database operations.
Shortcut Insert (INSERT)
$data = array(
‘title‘ => $title,
‘name‘ => $name,
‘date‘ => $date
);
$this->db->insert(‘mytable‘, $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES (‘{$title}‘, ‘{$name}‘, ‘{$date}‘)
Database QuickStart Example code