tags:

views:

314

answers:

3

What is the difference between the quotes " and ' ? What about `? Is there an error in using different quotes ' and " below?

 $result = pg_query_params($dbconn,
      'INSERT INTO users 
      (username, email, passhash_md5)
      VALUES ($1, $2, $3)',
          array($username, $email, $passhash_md5
      )


      $result = pg_query_params( $dbconn,
          "SELECT user_id
           FROM users
          WHERE email = $1",
          array( $email )
          )
+2  A: 

The difference between single and double quoted strings is well explained in the PHP manual about Strings.

In your example, since you are using substitution variables such as $1 that mean something specific to pg_query_params and that you do not want PHP to interpret as variable names, you should use single quotes for your SQL query strings.

Greg Hewgill
+1  A: 

Basically, " lets you embed variables like so:

<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers";   // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>

(From the php manual)

Using ' means that no checking for variables is done.

<?php
echo '$beer';
?>

Would output $beer.

Rich Bradshaw
+6  A: 

Variable-substitution isn't done when using single quotes ('), meaning that the values in your first example would literally be $1 $2 etc if it was a regular string and not passed on to a function that replaces them.

If you don't need variable-substitiution, it's better to stick with single quotes for performance reasons.

`` invokes the shell-engine and invokes it as an actual command, and returning the result, just like in perl. Hence, it has a completely different meaning.

examples:

$email = '[email protected]';
$sql1 = "SELECT user_id FROM users WHERE email = $email";
$sql2 = 'SELECT user_id FROM users WHERE email = $email';

$sql1 would be SELECT user_id FROM users WHERE email = [email protected]

$sql2 would be SELECT user_id FROM users WHERE email = $email

jishi
Escapes to control chars, like \n and \t are not expanded in single quote strings, too.
PhiLho
Strings like `$sql1` always make me cringe. If you _really_ want to include a variable in it, using `{$email}` always gets my preference. My usual approach: `"WHERE email = ".$email`, wich makes it absolutely clear that it is NOT to be taken literally.
JorenB
Of course none of those ways are safe against SQL injection, whatever you call the variable! The OP has it right, using $1 et al to pg_query_params in single quotes; no variable-substitution is actually occurring here. The ‘$1’ syntax is perhaps a little misleading... other query parameterisation systems just use ‘?’.
bobince