Reputation: 3777
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?
Upvotes: 0
Views: 100
Reputation: 5605
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"));
Upvotes: 2
Reputation: 11215
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"));
Upvotes: 2