問題描述
可以綁定表名嗎?
我想創(chuàng)建一個類來讀取表中的列,并根據(jù)字段類型為我生成表單輸入.當(dāng)我執(zhí)行 $form = new form("users");
時,構(gòu)造函數(shù)應(yīng)該從使用以下代碼從表中獲取字段名稱開始:
I want to make a class to read the columns from a tables and, depending on field type, generate the form inputs for me. When I do $form = new form("users");
, the constructor is supposed to start with getting the field names from the table with the following code:
class form{
public function __construct($table, $skip = array("id")){
$pdo = new PDO('mysql:host=localhost;dbname=site;',USER,PASS);
$query = $pdo->prepare("DESCRIBE :table");
$query->bindValue(':table', $table, PDO::PARAM_STR, strlen($table));
$query->execute();
while($field = $query->fetch(PDO::FETCH_NUM)){
var_dump($field);
echo "<br /><br />";
}
unset($pdo);
}
}
當(dāng)我在準(zhǔn)備語句中指定users"而不是:table"時,這工作得很好,但是綁定它正在工作,我很確定這是因為它試圖綁定一個表名.此外,這需要綁定,因為我希望能夠通過 $_GET
等傳遞我的表名.
This works just fine when I specify "users" instead of ":table" in the prepare statement, but the bind it's working, and I'm pretty sure it's because it's trying to bind a table name. Also, this needs to be binded because I'd like to have the ability to pass my table names through $_GET
and the such.
推薦答案
可以綁定表名嗎?
Is it possible to bind a table name?
沒有
您必須將表名列入白名單.我懷疑您是否想讓用戶從您的數(shù)據(jù)庫中瀏覽任何 表.
You have to whitelist table names. I doubt you want to let a user to browse any table from your database.
而且您還必須手動格式化標(biāo)識符.有一個帶有示例的 tag wiki.為什么不先讀呢?
And you have to format identifiers manually as well. There is a tag wiki with example. Why not read it first?
更新:如您所見,PDO 對于現(xiàn)實生活中的任務(wù)來說并不方便.所以,你必須有一個更智能的抽象庫來處理 MySQL 查詢.下面是一個使用 safeMysql 類的示例,它可以顯著縮短您的代碼:
Update: As you can see, PDO turns out to be inconvenient for real life tasks. So, you have to have a more intelligent abstraction library to handle MySQL queries. Here is an example using the safeMysql class, which will make your code dramatically shorter:
class form{
public function __construct($table){
global $db;
return $db->getAll("DESCRIBE ?n", $table);
}
}
2 條注釋:
- 我刪除了第二個參數(shù),因為您的函數(shù)中沒有使用它的代碼.
- 永遠(yuǎn)不要在課堂上聯(lián)系.請改用已打開的連接.或者你會用這么多連接殺死你的 MySQL 服務(wù)器.
排除已實現(xiàn)的版本
class form {
public function __construct($table,$skip = array("id")){
global $db;
$data = array();
$res = $db->query("DESCRIBE ?n", $table);
while($row = $db->fetch($res)) {
if (!in_array($row['Field'],$skip)) {
$data[] = $row;
}
}
return $data;
}
}
然而,這樣的類很少可以按預(yù)期使用 - 總是有很多例外和手動格式化才能使其可用.
However, such class seldom can be used as intended - there are always a lot of exceptions and manual formatting to make it usable.
這篇關(guān)于PHP PDO - 綁定表名?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!