我需要使用从 URL 中提取的多个参数设置 SQL 查询。到目前为止,我只能让它与 URL 中只有一项一起使用。
我的默认查询拉入所有内容
$sql = "SELECT ";
$sql .= "* ";
$sql .= "FROM ";
$sql .= "cms_site_content ";
$sql .= "WHERE ";
$sql .= "1";
然后我检查是否有任何内容通过 URL 传递并检索它。
if (isset($_GET["d"])) {
$d=$_GET["d"];
在 if 语句中,我将作为“d”传递的值分解为单独的项
$newD = explode(',',$d);
$countD = count($newD);
foreach($newD as $discipline) {
if ($countD == 1) {
$sql .= " AND";
$sql .= " discipline='".$discipline."'";
}
我的问题是在有多个规程值时让 SQL 工作。它应该是这样的:
SELECT * FROM cms_site_content WHERE 1 AND discipline="value"
然而,如果有不止一个纪律值,它应该是:
SELECT * FROM cms_site_content WHERE 1 AND discipline="value OR discipline="value2" OR discipline="value3"
有没有更有效的写法?我不知道如何将 OR 插入到 foreach 语句中。
最佳答案
将所有学科值保存在一个数组中;
$discipline_arr = array();
foreach($newD as $discipline) {
$discipline_arr[] = $discipline;
// by the way, don't forget to escape for sql injection
// mysql_escape_string is the depracated one, u can use that if u have no
// other choice
}
然后在你的 sql 中,将它们添加为 discipline in ('value1','value2', 'etc ...') 条件(对于字符串,对于数字类型,它就像 discipline in (1,2, 3,4 等)
$sql = " SELECT * FROM cms_site_content WHERE 1 " .
(empty($discipline_arr) ? "" : "and
discipline in ('". implode("','" , $discipline_arr). "') ") ;
转义链接 http://tr1.php.net/manual/en/function.mysql-escape-string.php
关于php - 使用多个参数设置 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21687988/