3

Ive been learning codeigniter and I like their database methods. However I would prefer to write my own SQL queries. When I try to write a manual query it results in a codeigniter error.

Ive searched around if it is possible however I cant find much info on the subject. The closes Ive come to an answer was this.

Question

Is it possible to disable the build in Codeigniter database methods, and perform my own sql queries. Or run my own sql queries alongside CodeIgniter's database class?

If yes, how would I go about configuring this?

Thanks in advance

Marilee
  • 1,598
  • 4
  • 22
  • 52
  • Maybe pulling the underlying PDO connection out?.. Wait this looks promising [How to refer to database connection in codeigniter?](https://stackoverflow.com/questions/10273550/how-to-refer-to-database-connection-in-codeigniter) – ficuscr May 11 '18 at 03:33
  • Did you tried using the `query' method of CodeIgniter database Class? – muecas May 11 '18 at 03:33
  • @muecas I have but it still does not give me "total control / the flexibility I want" – Marilee May 11 '18 at 03:35
  • What's more flexible than writing your own sql queries? – muecas May 11 '18 at 03:44
  • $query = $this->db->query(" SELECT name FROM user");//put your queries here and do var_dump($query) , and please share result or error – Kamalesh M. Talaviya May 11 '18 at 03:55
  • 1
    Possible duplicate of [How to execute my SQL query in CodeIgniter](https://stackoverflow.com/questions/16435390/how-to-execute-my-sql-query-in-codeigniter) – Wolfie May 11 '18 at 03:56

3 Answers3

4

From https://www.codeigniter.com/userguide3/database/results.html, you can use query method from db library.

$query = $this->db->query("YOUR QUERY");

foreach ($query->result() as $row)
{
        echo $row->title;
        echo $row->name;
        echo $row->body;
}
  • So I can do Joins and perform all other SQL queries within the `query` method? What about binding parameters? – Marilee May 11 '18 at 03:57
  • 1
    Yeah, you can perform all SQL queries within query. For binding parameters, you can try like this `$this->db->query("UPDATE user SET ip_whitelist=NULL WHERE username=?", [$this->session->userdata('username')]);` – Galih Akbar Moerbayaksa May 11 '18 at 03:59
  • 1
    @Marilee `$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?"; $this->db->query($sql, array(3, 'live', 'Rick'));` bind params – Rejoanul Alam May 11 '18 at 04:10
0

$this->db->query('selec * from your_table');

you can use like this your core query ...

Girish Ninama
  • 583
  • 4
  • 8
-2

This may help you out

`

$sql = "select model,varient,(select color from mtbl_colors where
        mtbl_colors.colorid=mtbl_vehicles.colorid) as color from mtbl_vehicles";

$sql .= " where $where_clause = ?"; $result = $this->db->query($sql, $where_value);

`