2

当我想查询数据库时遇到问题,在这种情况下,我想使用 IN() mysql 函数按数组上的值字段搜索数据。

例如我有来自 php 的数组

$data = array(1,2,3,4);

这是我在表 Employee 上选择数据的查询代码

$query = 'SELECT * FROM employee_tbl 
    -> WHERE daily_typing_pages IN ' .$data.;

当我执行该代码时,我有这样的错误

Syntax error or access violation: 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 'Array 
SELECT * FROM employee_tbl 
        -> WHERE daily_typing_pages IN Array;

我认为错误是因为数组读取为字符串,并且不解析为这种格式(1,2,3,4)

我怎样才能转换成那种格式?有什么建议吗?

4

4 回答 4

2

用于implode()将项目的实际逗号分隔列表创建为字符串。

$query = 'SELECT * FROM employee_tbl 
    -> WHERE daily_typing_pages IN (' . implode(",", $data) . ")";
于 2012-10-08T03:55:48.577 回答
2

尝试,

$data = array(1,2,3,4);
$ids = join(',',$data);  
$sql = "SELECT * FROM employee_tbl WHERE daily_typing_pages IN ($ids)";
于 2012-10-08T03:58:41.550 回答
1

试试这个代码,用于implode()将数组转换为字符串

 $query = "SELECT * FROM employee_tbl 
        -> WHERE daily_typing_pages IN  ( ".implode(',',$data)." ) ";
于 2012-10-08T03:56:06.863 回答
1

利用implode()

$x = array(1,2,3,4);
$y = implode(',',$x);
于 2012-10-08T03:56:28.533 回答