我在发布此内容之前进行了搜索,但没有找到问题的答案。
我在数据库中有一个表,它存储了诸如(将 php 变量存储在数据库中)之类的查询:
select * from accounts where type = 'client'
select * from accounts where user_id = $userid
select * from accounts where name = '$name'
我假设当我从数据库中提取该特定查询时,PHP 会识别该变量并替换它,但它将其视为常规文本。
有没有办法让 PHP 用存在的实际变量替换 $__?我想也许是 eval() 函数??
您可以尝试将其用作预准备语句。因此,如果您的数据库存储查询如下所示:
select * from accounts where type = 'client'
select * from accounts where user_id = ?
select * from accounts where name = ?
并且您使用PDO准备语句,如下所示:
$pdo = new PDO($dsn, $user, $pass);
$statement = $pdo->prepare($secondOfTheAboveQueries);
$statement->execute(array($userId));
$account = $statement->fetch();
如果必须一次处理具有各种变量的几个语句,还可以将准备好的查询与命名变量(如 user_id = :userid
)一起使用,而不是问号。
您可能还需要考虑工作方式类似的存储过程。可以在此处找到两者的解释:
http://php.net/manual/en/pdo.prepared-statements.php
假设您从数据库中提取查询:
$string = ''; // Assign the real userID
while ($fetch = mysql_fetch_array($query)) {
$newQuery = str_replace('$userid', $string, $fetch['your_row_name']);
}
我不确定这是否有效,但这是我首先要尝试的......
冲刺似乎运行良好。 我可以使用 %s 等,而不是将它们存储为 $variable。