2012-04-24 70 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等。