Database Select
Database Select is a feature of CodeIgniter Database that allows for the selection of data from a database table. With Database Select, users can retrieve data from a database table based on certain conditions.
Syntax
The basic syntax for Database Select is as follows:
$this->db->select('column_name_1, column_name_2');
$this->db->from('table_name');
$this->db->where('condition_1', 'condition_2');
$query = $this->db->get();
return $query->result();
In the above example, column_name_1
and column_name_2
refer to the columns to be selected from the table_name
table. The where
clause specifies the conditions that must be met in order for the data to be retrieved. The get()
function executes the query, and result()
returns an array of objects containing the retrieved data.
Example
Consider the following database table named employees
:
id | name | age | gender |
---|---|---|---|
1 | John | 28 | Male |
2 | Jane | 35 | Female |
3 | Mark | 42 | Male |
To select the name
and age
columns of all employees who are older than 30, the following code can be used:
$this->db->select('name, age');
$this->db->from('employees');
$this->db->where('age >', 30);
$query = $this->db->get();
return $query->result();
This will return the following output:
[
{
"name": "Jane",
"age": "35"
},
{
"name": "Mark",
"age": "42"
}
]
Explanation
In the example above, the select()
function is used to specify that only the name
and age
columns should be retrieved from the employees
table. The where()
function specifies that only employees with an age
greater than 30 should be selected. The get()
function executes the query, and the result()
function returns an array of objects containing the selected data.
Use
Database Select is a useful feature of CodeIgniter Database that allows for the retrieval of data from a database table based on specified conditions. It is particularly useful when you need to retrieve specific pieces of data from a large table.
Important Points
- Queries using Database Select must be properly formatted to avoid SQL injection attacks.
- Database Select can be combined with other CodeIgniter functions such as
limit()
andorder_by()
for more precise querying. - Resulting data can be returned as an array or as an object.
Summary
Database Select is a feature of CodeIgniter Database that allows for the retrieval of data from a database table based on specified conditions. Queries must be properly formatted to avoid SQL injection attacks, and can be combined with other CodeIgniter functions for more precise querying. Resulting data can be returned as an array or as an object.