2013-02-20 14 views
0

我有一個值的數組,我想用mysql IN()函數檢查,但是如何在codeigniter中使用它?使用mysql中的()函數

這就是我目前正在做的事情,這顯然不起作用。

$p = array('page1', 'page2', 'page3','page4', 'page5'); 
$pages = implode(",", $p); 

$sql = "select page from pages where domains_id = ? and page in(?) and is_deleted=0"; 
$fields = array($domains_id, $pages); 

$this->db->query($sql, $fields) 

the output of the pages variable comes out to page1,page2,page3,... but the in function needs them seperated like this: 
'page1','page2','page3'.... 

回答

1
<?php 
function addQuotes($string) 
{ 
    return "'{$string}'"; 
} 
$p = array('page1', 'page2', 'page3','page4', 'page5'); 
$p2 = array_map("addQuotes", $p); 

print_r($p2); 

See it in action

然後,您可以使用您的implode()正常。

0

開始與外部的報價與','

$pages = sprintf("'%s'", implode("','", $p)); 
+0

這會不會導致應用程序容易受到SQL注入? – MikeB 2013-02-20 23:53:20

+0

@MikeB - 取決於$ p來自哪裏 – Galen 2013-02-21 00:23:14

+0

這意味着您必須追蹤它,而不是僅僅採用安全的方式並確保它是正確的。看起來像一個陷阱。 – MikeB 2013-02-21 15:19:34

0

的破滅試試這個:

$p = array('page1', 'page2', 'page3','page4', 'page5'); 
$this->db->select('page'); 
$this->db->from('pages'); 
$this->db->where('domains_id', $domains_id); 
$this->db->where_in('page', $p); 
//Note where_in function expects 2nd parameter as array 
$this->db->where('is_deleted', '0'); 

$query = $this->db->get(); 

有關詳細信息: http://ellislab.com/codeigniter/user-guide/database/active_record.html