8

Im trying to select some values using a custom string. below is my code

  $this->db->from('posted');
  $st="infor='rent' AND (typeq='in' OR typeq='out')";
  $this->db->where($st);  
  $q = $this->db->get();  

A Database Error Occurred

Error Number: 1054

Unknown column ‘infor=‘rent’’ in ‘where clause’
SELECT * FROM (`posted_ads`) WHERE `infor=‘rent’` AND (typeq=‘in’
 OR typeq=‘out’)
Filename: C:\wamp\www\parklot\system\database\DB_driver.php
Line Number: 330

i think the problem is coz of

WHERE `infor='rent'` 

when i manualy execute this code it works perfectly.

WHERE infor='rent' 

how do i get rid of

`` 

because its automatically added

0

2 Answers 2

23

Add a third parameter to the where() and set it to FALSE

  $this->db->from('posted');
  $st="infor='rent' AND (typeq='in' OR typeq='out')";
  $this->db->where($st, NULL, FALSE);  
  $q = $this->db->get();

$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.

CodeIgniter Documentation

Sign up to request clarification or add additional context in comments.

4 Comments

If you do similar things often, useful to create a function which add ticks around the table names and fields - or write a simple wrapper-function which calls db->where with proper ticks (with false third parameter of course).
It's a shame that this isn't in the docs here. ellislab.com/codeigniter/user-guide/database/active_record.html
@user1253085 It's in there. You must've overlooked.
I see it now. At the very, very bottom. I'm used to docs defining function usage and available params and options before showing examples.
0

While the solution works I wanna add: Be careful! You need to secure your query and escape all values! If you like to use the Query Builder

$q = $this->db->select('*')->from('posted_ads')
    ->where('infor', 'rent')
    ->or_group_start()
            ->where('typeq', 'in')
            ->where('typeq', 'out')
    ->group_end()
->get();

This way Codeigniter takes care of proper escaping.

1 Comment

Did you test this? What was the rendered SQL?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.