CodeIgniter ActiveRecord join() method wrapping nu

2019-05-23 21:48发布

问题:

This is my active record code in CodeIgniter:

$this->db->...
$this->db->join('post_likes', 'post_likes.user_id="'.$this->db->escape($online_user).'" AND post_likes.post_id=post.id', 'left');

And this is how it is interpreted:

LEFT JOIN `post_likes` ON `post_likes`.`user_id`="`3"` AND post_likes.post_id=post.id

it gives the error:

`user_id`="`3"` 

How to write a direct number in active record?


Update:

removing escape

to test it on your computer you dont need to have a database. Just trying this code shows the error:

$this->db->select('*')
    ->from('mytable')
    ->join('post_likes', 'post_likes.user_id="3" AND  post_likes.post_id=post.id', 'left');
$query=$this->db->get('');
var_dump($this->db->last_query());
exit(0);

result:

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '` AND post_likes.post_id=post.id' at line 3

SELECT * FROM (`mytable`) LEFT JOIN `post_likes` ON `post_likes`.`user_id`="`3"` AND post_likes.post_id=post.id

回答1:

You SHOULD not use the double quotes in SQL query:

$this->db->join('post_likes', "post_likes.user_id = $online_user AND post_likes.post_id=post.id", 'left');

Update:

This is a bug in the current CI stable version (fixed in v3.0-DEV), CI ActiveRecord methods (which doesn't implement really ActiveRecord) are prepared for simple usages.

I fixed this issue before by hacking the core files (by adding a parameter to join method to disable _protect_identifires).

There we go:

In system/database/DB_active_rec.php line #310, add $escape as 4th parameter:

public function join($table, $cond, $type = '', $escape = TRUE)

And change $match[3] = ... to:

if ($escape === TRUE)
{
    $match[3] = $this->_protect_identifiers($match[3]);
}

So, you can use join($table, $cond, $type = '', $escape = FALSE) to disable escaping.

In addition, setting _protect_identifires globally to FALSE is not in a correct direction.

the only option remains is using custom query():

$sql = "SELECT * FROM some_table WHERE id = ?"
$this->db->query($sql, array(3));


回答2:

Try this

    $this->db->join('post_likes', "post_likes.user_id=$the_userid AND 
     post_likes.post_id=post.id", 'left');

or

 $this->db->join('post_likes', 'post_likes.user_id="'.$the_userid.'" AND 
         post_likes.post_id=post.id', 'left');

Update:

Define

$db['default']['_protect_identifiers']= FALSE; 

in "application/config/database.php" at the end.



回答3:

try this one

$this->db->join('post_likes', 'post_likes.user_id="{$online_user}" AND post_likes.post_id=post.id', 'left');

please let me know if you face any problem.



回答4:

Dont use $this->db->escape

$this->db->join('post_likes', 'post_likes.user_id="'.$online_user.'" AND post_likes.post_id=post.id', 'left');