The following page contains example code showing how the database class is used. For complete details please read the individual pages describing each function.
The following code loads and initializes the database class based on your configuration settings:
$this->load->database();
Once loaded the class is ready to be used as described below.
Note: If all your pages require database access you can connect automatically. See the connecting page for details.
$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 above result() function returns an array of objects. Example: $row->title
$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 above result_array() function returns an array of standard array indexes. Example: $row[‘title’]
$query = $this->db->query('SELECT name FROM my_table LIMIT 1'); $row = $query->row(); echo $row->name;
The above row() function returns an object. Example: $row->name
$query = $this->db->query('SELECT name FROM my_table LIMIT 1'); $row = $query->row_array(); echo $row['name'];
The above row_array() function returns an array. Example: $row[‘name’]
$sql = "INSERT INTO mytable (title, name) VALUES (".$this->db->escape($title).", ".$this->db->escape($name).")"; $this->db->query($sql); echo $this->db->affected_rows();
The Query Builder Pattern gives you a simplified means of retrieving data:
$query = $this->db->get('table_name'); foreach ($query->result() as $row) { echo $row->title; }
The above get() function retrieves all the results from the supplied table. The Query Builder class contains a full compliment of functions for working with data.
$data = array( 'title' => $title, 'name' => $name, 'date' => $date ); $this->db->insert('mytable', $data); // Produces: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}')
© 2014–2018 British Columbia Institute of Technology
Licensed under the MIT License.
https://www.codeigniter.com/user_guide/database/examples.html