2014-04-14 39 views
0

我遇到了一些問題。 這裏我請求(它的工作):無法用SQL查詢中的變量替換表名稱

$reponse = $bdd->prepare('select * from student where UserName = ? and Password = ? '); 
$reponse->execute(array($name,$pass)); 

它的工作,但是當我想一個PHP變量它沒有按牛逼的作品,以取代「學生」:/ 看:

$table="stackoverflow" 
$reponse = $bdd->prepare('select * from '$table' where UserName = ? and Password = ? '); 
$reponse->execute(array($name,$pass)); 

你有一個想法?如果我可以用變量替換表名,這會更簡單。 抱歉我的英文不好。 謝謝你花費在我身上的時間。

+0

請**不要**使用' SELECT *'在你的應用程序中,總是寫出每個列名。 – Twinkles

回答

3

在PHP中,你加入兩個字符串或變量通過一個句點字符(。)。

因此,以連接表名和前和表名後您的語句,你應該改變這行

$reponse = $bdd->prepare('select * from '$table' where UserName = ? and Password = ? '); 

$reponse = $bdd->prepare('select * from '.$table.' where UserName = ? and Password = ? '); 
+0

非常感謝! – user3527069

+0

@ user3527069非常歡迎您! :) – shrmn

5

更改此:

$reponse = $bdd->prepare('select * from '$table' where UserName = ? and Password = ? '); 

要:

$reponse = $bdd->prepare("select * from `$table` where UserName = ? and Password = ? "); 
+3

如果標識符用單引號包裝,這將不起作用。只要'select * from $ table where ...' –

+0

那麼,這將打印:select * from'stackoverflow'where ... and it will ... –

+0

同意你@JohnWoo –

0

由於表名是一個字符串,試戴

"SELECT * FROM from \"".$table."\" WHERE ....... ";