2

I searched before posting this but didn't find an answer to my question.

I have a table in a database which stores queries such as (with the php variable stored in the database):

select * from accounts where type = 'client'
select * from accounts where user_id = $userid
select * from accounts where name = '$name'

I assumed that when I pulled that particular query from the database that PHP would recognized the variable and replace it but it treats it as regular text.

Is there a way to have PHP replace the $__ with an actual variable that exists? I think maybe the eval() function perhaps??

4

3 回答 3

1

您可能会尝试将其用作准备好的语句。因此,如果您的数据库存储的查询如下所示:

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

于 2012-04-24T18:23:05.240 回答
0

sprint 似乎运作良好。我可以使用 %s 等,而不是将它们存储为 $variable。

于 2012-07-04T02:54:14.697 回答
0

假设您从数据库中提取查询:

$string = ''; // Assign the real userID

while ($fetch = mysql_fetch_array($query)) {

    $newQuery = str_replace('$userid', $string, $fetch['your_row_name']); 
} 

我不确定这是否可行,但这是我首先要尝试的...

于 2012-04-24T18:07:12.693 回答