$1和$2是什么意思?

4
这行代码中$1和$2代表什么?它们是变量吗?但是它们怎么能用在字符串里呢?
$query = "select * from php_project.student where student_num=$1 and student_pass=$2";

编辑:以下是接下来的几行:

        $stmt = pg_prepare($dbconn,"ps",$query);
        $result = pg_execute($dbconn,"ps",array($studentnum,$password));
        if (!$result){
            die("error in SQL query:".pg_last_error());
        }

1
这些是需要传递给查询的参数。 - Arun P Johny
但它们可以直接用在字符串中吗?比如在Ruby中的字符串插值? - Chin
5
这是一个非常糟糕的设计决策——使用 $n 来作为占位符。 - zerkms
@Chin 这个查询有效吗? - egig
代码中是否在某处将$query传递给了preg_*函数? - Sverri M. Olsen
@zerkms,这是使用官方PostgreSQL客户端库在本地PHP中正确的实现方式。我同意,这非常奇怪。 - methai
1个回答

8

$1和$2不是变量。它们在字符串中被用作占位符。

在PHP中,$(数字)不是变量。你可以自己试试:

$1 = "bob";
>> Parse error: syntax error, unexpected T_LNUMBER, expecting T_VARIABLE or '$' in PHP shell code on line 1

所以"$1"实际上是一个字符串,它的内容为"$1"。
你可以使用str_replace函数,得到如下结果:
PHP > echo str_replace("$1", "'Bob'", $query);
>> select * from php_project.student where student_num='Bob' and student_pass=$2

更新

根据您的更新,pg_prepare实际上是这样说的:

如果使用了任何参数,则在查询中将其表示为$1、$2等。

因此,在您的情况下,array($studentnum,$password)基本上用'$studentnum'替换$1,并用'$password'替换$2,但它还正确转义值以防止SQL注入攻击。

http://php.net/manual/en/function.pg-prepare.php


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接