views:

37

answers:

4

So, I can run the following statements from within mysql itself successfully.

SET @fname = 'point1';
SELECT * FROM country WHERE name=@fname;`

But when I try to pass the query through php like this and run it, I get an error on the second line

$query = "SET @fname = 'point1';";

$query  .=  "SELECT * FROM country WHERE name=@fname;";
+1  A: 

I am not certain why it fails, but rather than writing it with MySQL variables, why not use PHP variables?

In other words,

$fname = 'point1';
$query = "select * from country where name = '$fname'";

And the normal warning against SQL injection applies, of course.

MJB
Could also use a prepared statement which would kill SQL injection altogether
Pier-Luc Gendreau
Yeah, I agree. I was trying to keep it simple.
MJB
+2  A: 

You can't run multiple statements through PHP's mysql libraries without using a special function. But your SQL variable should persist through your connection, so instead of concatenating the strings and running once, execute each statement separately.

Matt S
I didn't know they would persist. In Oracle they die (AFAIK)
MJB
Special function meaning code that parses and separates your statements and runs the queries separately for you.
webbiedave
There is the mysqli_multi_query function, but I don't recommend it.
Matt S
A: 

Also have a look at this and this comments at mysql_query() doc page.

hudolejev
+1  A: 

PHP's mysql drivers do not allow multiple queries to be executed from a single query function call as a security measure. It's a partial mitigation against the worst of SQL injection attacks, making the classic XKCD Bobby Tables attack ineffective.

That's not to say that it makes injection attacks impossible - it just makes the multi-query version of the attacks impossible.

Marc B