0

I want to supply a SQL statement from the query string, but all my efforts result in escaped single quotes and slashes.

7
  • 1
    Please show us your code, your input and your output. Commented Jun 1, 2010 at 15:54
  • 4
    If I'm reading your question correctly, then I would strongly advise against taking a SQL query in a query string. Commented 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 => query Commented 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? Commented 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? Commented Jun 1, 2010 at 16:02

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you are using mysql, use mysql_real_escape_string()

http://www.php.net/manual/en/function.mysql-real-escape-string.php

Comments

0

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";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.