我正在尝试将ORDER BY语法添加到我在PHP中执行的MySQL连接查询中。我正在使用已定义的会话变量来动态选择条件。
工作正常:
$query_icons = sprintf("SELECT i.id, i.name, e.EmpNo FROM gbl_icons i LEFT JOIN gbl_empicons e ON e.IconId = i.id AND e.EmpNo = %s", GetSQLValueString($ParamEmpNo_WADAgbl_qemplisting, "text"));
当我尝试追加ORDER BY时,会抛出500内部服务器错误:
$query_icons = sprintf("SELECT i.id, i.name, e.EmpNo FROM gbl_icons i LEFT JOIN gbl_empicons e ON e.IconId = i.id AND e.EmpNo = %s", GetSQLValueString($ParamEmpNo_WADAgbl_qemplisting, "text")ORDER BY i.id ASC);
如何正确地正确转义动态会话值?
答案 0 :(得分:2)
这样做:
$query_icons = sprintf("SELECT i.id, i.name, e.EmpNo FROM gbl_icons i LEFT JOIN gbl_empicons e ON e.IconId = i.id AND e.EmpNo = %s", GetSQLValueString($ParamEmpNo_WADAgbl_qemplisting, "text")."ORDER BY i.id ASC");
你忘了将ORDER BY i.id ASC包围在“这样你就会出现严重的语法错误
正如评论中提到的那样,这也会起作用:
$query_icons = sprintf("SELECT i.id, i.name, e.EmpNo FROM gbl_icons i LEFT JOIN gbl_empicons e ON e.IconId = i.id AND e.EmpNo = %s ORDER BY i.id ASC", GetSQLValueString($ParamEmpNo_WADAgbl_qemplisting, "text"));
答案 1 :(得分:2)
将ORDER BY放在字符串中,在“%s”之后。
作为补充,将SQL查询直接伪造成字符串是非常不安全的,尝试使用PDO或其他数据访问层来创建安全的参数化请求。
$query_icons = sprintf("SELECT i.id, i.name, e.EmpNo FROM gbl_icons i LEFT JOIN gbl_empicons e ON e.IconId = i.id AND e.EmpNo = %s ORDER BY i.id ASC", GetSQLValueString($ParamEmpNo_WADAgbl_qemplisting, "text"));