使用PHP使用IN子句查询MySQL [英] Querying MySQL with IN clause using PHP

查看:228
本文介绍了使用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.

这篇关于使用PHP使用IN子句查询MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆