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 Jun 01 '10 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 Jun 01 '10 at 15:56
-
yep, besides that you should never do that... work with actions... sorta like ?action=del => switch $action case: del => query – Toby Jun 01 '10 at 15:57
-
I'm creating a generic php webservice. It's basically a wrapper for mysql. This is not a good idea? – cmaduro Jun 01 '10 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 Jun 01 '10 at 16:02
-
So that I can access it from a Silverlight client. – cmaduro Jun 01 '10 at 16:02
-
If this is not a good idea, then how can I implement this in a generic way? – cmaduro Jun 01 '10 at 16:03
3 Answers
First, make sure you really really want to do that. This is ripe for an SQL Injection attack.
If you want something to run statements against the MySQL database, just use phpMyAdmin or MySQL workbench.

- 8,842
- 8
- 41
- 56
Assuming you are using mysql, use mysql_real_escape_string()
http://www.php.net/manual/en/function.mysql-real-escape-string.php

- 4,293
- 6
- 37
- 65
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";

- 1
- 1

- 156,878
- 40
- 214
- 345