I am trying to add a ORDER BY syntax to a MySQL join query I am performing in PHP. I am using an already defined session variable to dynamically select criteria.
Works fine:
$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"));
When I try to append ORDER BY it throws a 500 Internal Server Error:
$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);
How do I properly escape the dynamic session value properly?
do this:
$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");
you forgot to enclode the ORDER BY i.id ASC in " so that you got a serious syntax error
as mentiond in the comment this would work too:
$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"));
put the ORDER BY inside the string , after the "%s".
as an addition, it's very unsafe to forge SQL queries into a string directly, try using PDO or other data access layer to create safe parameterized requests.
$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"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.