7

I need to execute this query with Codeigniter query builder:

SET @row_number:=0;

SELECT Id, @row_number:=@row_number+1 as Position
FROM my_table
WHERE date='2015-12-26'

I can do it by using "$this-> db-> query" function like this:

$query = 'SET @row_number:=0;';
$this-> db-> query ($query);
    
$query = 'SELECT Id, @row_number:=@row_number+1 as Position';
$query = $query . ' FROM my_table';
$query = $query . ' WHERE date=\'' . $data . '\''

But, my question is: Is there a way to do it without hard write the query, so writing something like this:

$query = 'SET @row_number:=0;';
$this->db->query ($query);
#*****It's wrong!!!!*****
    
$this->db->select(array('Id', '@row_number:=@row_number+1 as Position'));
$this->db->from('my_table');
$this->db->where('date', $data);
$query = $this->db->get();

2 Answers 2

2

No need to pass array in select you just write your query as

 $this -> db -> select('Id, @row_number:=@row_number+1 as Position');
Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't work because generated query is like this: SELECT 'Id', '@row_number:=@row_number+1' as Position FROM 'my_table'. I think there are two problems: 1-It doesn't consider the first part of query (SET @row_number:=0). 2-Using your solution it attaches quotes like '@row_number:=@row_number+1'
0

Personally, I would prefer to order the results by some column and add the desired position in a foreach loop, cause it's more efficient and it keeps the code cleaner imo, nevertheless it is possible.

The key to the solution is the second, optional parameter of the CI db select function, as it is pointed out in the user guide:

$this->db->select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names. This is useful if you need a compound select statement where automatic escaping of fields may break them.

Like so:

$query = 'SET @row_number := 0';
$this->db->query($query);

$this->db->select(array('Id', '@row_number:=@row_number+1 as Position'), false);
$this->db->from('my_table');
$this->db->where('date', $data);
$query = $this->db->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.