PHP: different quotes?

こ雲淡風輕ζ 提交于 2019-12-17 07:49:12

问题


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 )
          )

回答1:


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 = 'user@example.org';
$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 = user@example.org

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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1318028/php-different-quotes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!