A: 

If you use a variable - especially an associative array - in a string, you can be quite sure that it will lead to errors. It's just bad style. I - personally - don't like the second alternative either.

sprintf( '... %d ...', $_GET[ 'id' ] );

That's my favorite way of putting a variable into a string.

okoman
+2  A: 

Using either of these directly in a SQL statement is a VERY BAD IDEA. It allows for SQL injections. Be sure to sanitize your inputs using something like mysql_real_escape_string.

The main difference between the two is that the top can only be used inside a string that uses double quotes. The bottom, however, can be used with either double or single quotes.

Evan Fosmark
+2  A: 

As far as I know there's no difference, but should you be doing that? You're allowing unsanitised input into your sql query which means if your website is internet facing you're leaving it wide open to sql injection attacks.

Here's a Q&A you should read before going any further:

http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php

Kev
+5  A: 

Its always a bad idea to put data from a get request directly into SQL, and there are many easy ways to prevent SQL injection.

For the simple case where you know you want a numeric ID, then you can simply for the value to be numeric and then there is no chance of SQL injection. One way might be okoman's usage of sprintf(), maybe something like this:

$sql = "INSERT INTO table VALUES(".sprintf("%d",$_GET['id']) .")";

though I think its ugly and bad form. Something like this is nicer:

$sql = "INSERT INTO table VALUES(".(int)$_GET['id']) .")";

Which simply casts the value to an int - if its not a number that can be cast to int - you'll get a "0" which may or may not be what you want.

Other alternatives (and for when your data is not supposed to be a number) include using escaping functions such as add_slashes() or the above mentioned mysql_real_escape_string().

IMHO, the best way to use database access from within PHP and very easily protect from SQL injection is to use the new PHP PDO library ( http://php.net/PDO ). This allows you to write SQL strings that contain to data whatsoever, and have the data added later inside the database server itself. In this form there is absolutely no way to do SQL injection.

Here is some example code:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO table VALUES (?)");
$stmt->bindParam(1, $_GET['id']);
$stml->execute();

As you can see, the data is not added to the SQL query itself and so no need for escaping.

Guss