使用PHP使用IN子句查询MySQL
我想进行类似于以下的查询:
I want to do a query similar to the following:
SELECT f_name, l_name, title from
-> employee_data where title
-> IN ('Web Designer', 'System Administrator');
搜索项在数组$data = ['Web Designer', 'System Administrator']
中接收,现在我可以使用以下命令将该数组转换为Web Designer,System Administrator
:
The search terms are received in an array $data = ['Web Designer', 'System Administrator']
and right now I can turn that array into Web Designer,System Administrator
using:
$data = implode(',', $data)
是否存在将数组转换为'Web Designer', 'System Administrator'
的好方法,因此我可以将此短语直接插入到MySQL查询中,如文章开头所示?
Is there a good way to turn that array into 'Web Designer', 'System Administrator'
so I can insert this phrase into the MySQL query directly as shown at the beginning of the post?
您可能应该使用:
$data = implode( ', ', array_map( $data, array( $object, 'escape')));
$query .= 'title IN ( ' . $data . ')'; // Append to condition
$object->escape()
的功能如下:
public function $escape( $string){
return "'" . mysql_real_escape_string( $string, $this->connection) . "'";
}
以下是 array_map()
文档和 SQL注入证明解决方案.
Here's array_map()
documentation, and mysql_real_escape_string()
. This should be SQL injection proof solution.