I want to supply a SQL statement from the query string, but all my efforts result in escaped single quotes and slashes.
-
1Please show us your code, your input and your output.Felix Kling– Felix Kling2010-06-01 15:54:57 +00:00Commented Jun 1, 2010 at 15:54
-
4If I'm reading your question correctly, then I would strongly advise against taking a SQL query in a query string.Ian P– Ian P2010-06-01 15:56:10 +00:00Commented Jun 1, 2010 at 15:56
-
yep, besides that you should never do that... work with actions... sorta like ?action=del => switch $action case: del => queryTobi– Tobi2010-06-01 15:57:52 +00:00Commented Jun 1, 2010 at 15:57
-
I'm creating a generic php webservice. It's basically a wrapper for mysql. This is not a good idea?cmaduro– cmaduro2010-06-01 15:59:18 +00:00Commented Jun 1, 2010 at 15:59
-
It's a hideous idea. Why would you want to wrap MySQL in a webservice? What's the use case?Steve Hill– Steve Hill2010-06-01 16:02:25 +00:00Commented Jun 1, 2010 at 16:02
3 Answers
Assuming you are using mysql, use mysql_real_escape_string()
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Comments
how can I implement this in a generic way?
All queries must be hardcoded in your script.
Of course some of them can be dynamically built, but you're allowed to make only DATA dynamic, not control structures.
So, it must be like this:
$name=mysql_real_escape_string($_POST['name']);
if ($id = intval($_POST['id'])) {
$query="UPDATE table SET name='$name' WHERE id=$id";
} else {
$query="INSERT INTO table SET name='$name'";
}
or this:
if (!isset($_GET['id'])) {
$query="SELECT * FROM table";
} else {
$id = intval($_GET['id'];
$query="SELECT * FROM table WHERE id=$id";
}
or whatever.
Of course, inserted data must be properly escaped, cast or binded.
But sometimes we need to use dynamic operator or identifier. The principle is the same: everything must be hardcoded in your script, nothing to be passed from the client side to the SQL query directly.
Say, to make a dynamic sorting, you can use a code like this
$orders=array("name","price","qty");
$key=array_search($_GET['sort'],$orders));
$orderby=$orders[$key];
$query="SELECT * FROM `table` ORDER BY $orderby";
or to assemble a dynamic WHERE:
$w=array();
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="select * from table $where";