2012-04-24 84 views
2

我在发布之前搜索过,但没有找到我的问题的答案。在MYSQL中使用PHP变量存储查询

我具有其中存储的查询,如(与存储在数据库中的PHP变量)的数据库中的表:

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

我假定当我把该特定查询从数据库PHP将识别该变量并将其替换,但将其视为常规文本。

有没有办法让PHP替换存在的实际变量$ _ _?我想也许eval()函数可能是?

+0

您从哪里执行脚本?为PHP变量工作,你应该执行你的SQL语句在PHP脚本 – 2012-04-24 17:12:42

+0

类似的问题:http://stackoverflow.com/questions/283222/best-way-to-substitute-variables-in-plain-text-using-php – Trevor 2012-04-24 17:13:48

回答

0

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

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

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

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

我不知道这是否会工作,但是这是我想尝试第一...

+0

我刚才意识到可能使用sprintf也可以做这项工作 – DeltaTango 2012-05-08 13:01:20

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

0

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