我正在生成一个API,它接受某些参数,执行算法并返回结果。作为此过程的一部分,我有几个不同的子句可以根据发送到API的内容进入SQL语句。这产生了这种格式的许多部分:
if(isset($_GET['val'])) {
$sqljoin = " INNER JOIN b ON b.1=a.1 "
$sqlwhere = " WHERE b.2 = " . $_GET['val'];
}
$sql = "SELECT * FROM a " . $sqljoin . $sqlwhere;
最初这很好,但现在我有大约6个不同的子句进入它,都有一个JOIN和一个WHERE子句。有没有更好的方法来构建它?
答案 0 :(得分:0)
$sql = "SELECT * FROM a ";
$where = " WHERE 1=1 ";
if(isset($_GET['val'])) {
$sqljoin = " INNER JOIN b ON b.1=a.1 "
$sqlwhere = " AND b.2 = " . $_GET['val'];
}
if(isset($_GET['val2'])) {
$sqljoin2 = " INNER JOIN b2 ON b2.1=a.1 "
$sqlwhere2 = " AND b2.2 = " . $_GET['val2'];
}
$fullquery = $sql . $sqljoin . $sqljoin2 . $where . $sqlwhere . $sqlwhere2 ;
一些注意事项:
您的代码是在sql注入漏洞下。你应该通过
来逃避你的变量$ _ GET [' val'] = mysql_real_escape_string($ _ GET [' val']);