Tags
Asked 3 years ago
17 Jun 2021
Views 247
Era

Era posted

How to write custom query in CodeIgniter

How to write custom query in CodeIgniter
debugger

debugger
answered Apr 27 '23 00:00

To write a custom query in CodeIgniter, you can use the $this->db->query() method and pass the SQL query as a string parameter.

Here's an example of how to write a custom query in CodeIgniter:



$query = "SELECT * FROM my_table WHERE column1 = ? AND column2 > ?";
$params = array($value1, $value2);

$result = $this->db->query($query, $params);

if ($result->num_rows() > 0) {
    foreach ($result->result() as $row) {
        echo $row->column1;
        echo $row->column2;
    }
}

In this example, we are selecting all columns from a table named " my_table " where "column1" equals a certain value and "column2" is greater than a certain value. We use the ? placeholder to indicate where the values of $value1 and $value2 should be inserted, and store those values in an array named $params.

We then pass the SQL query and the $params array to $this->db->query() , retrieve the results using $result = $this->db->query($query, $params), and loop through the results using a foreach loop to echo the values of each column.

You can modify the example to suit your specific query needs, changing the table name, column names, and where conditions as necessary. Note that you should properly sanitize any user input to prevent SQL injection vulnerabilities.
Post Answer