这行代码中的$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 和 $2 不是变量。它们被用作字符串中的占位符。
在 PHP 中 $(number first) 不是变量。自己试试:
$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 实际上是这样说的:
If any parameters are used, they are referred to in the query as $1, $2, etc.
因此,在您的情况下,array($studentnum,$password)
基本上在您的查询中将 $1 替换为“$studentnum”,将 $2 替换为“$password”,但它也会正确转义值防止 SQL 注入(inject)攻击。
关于php - 1美元和2美元是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15754611/