簡體   English   中英

我可以使用PDO參數化語句創建MYSQL表嗎?

[英]Can I create a MYSQL table using a PDO parameterized statement?

我希望使用PHP和PDO創建一個MySQL表。 我也希望參數化表名。 我已經嘗試實現這一點,下面顯示了有錯誤的代碼。

class databaseaccess {

    public $hostname = 'localhost';
    public $username = 'root';
    public $password = 'root';
    private $db = null;
    public $rows;

    public function __construct() {
        try {
                $this->db = new PDO("mysql:host=$hostname;dbname=noteshareproject", $this->username, $this->password);
        }
        catch (PDOException $Exception) {
            throw new Exception("DB failed to connect ".$Exception->getMessage());
        }
    }

    public function writetable($title,$id){
        if ($this->db === null) throw new Exception("DB is not connected");
        //query works with `:title` however keeps the commas. Gotta find out what is wrong.
        $query = "CREATE TABLE noteshareproject.:title (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), username VARCHAR(20)) ENGINE=myISAM;";
        $statement = $this->db->prepare($query);
        $title = $title . $id;
        $title = (string) $title;
        $statement->bindValue(':title', $title, PDO::PARAM_STR);
        $statement->execute();
        print_r($statement->errorInfo());
        echo $title;

    }
}

上面代碼的輸出如下:

Array
(
    [0] => 42000
    [1] => 1064
    [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''exampletablename'(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), username VARCHAR(20)) EN' at line >2
)
exampletablename

我在MySQL語法或PDO實現中做錯了什么?

您不能在准備好的語句中使用占位符作為標識符(列/表/數據庫/函數名稱等)。 您只能將它們用作值。

CREATE TABLE noteshareproject.:title
//                            ^^^^^^ this will not work

您將必須手動清理$title以便您可以直接在字符串中使用它。

還請注意,無法准備DDL語句(例如CREATE TABLE ,因此使用prepare()沒有意義。 您也可以只使用query()exec()

我也確實想知道您是否真的想這樣做表明數據庫設計不佳-盡管對您的信息一無所知,但對多個具有相同結構的表的要求不太可能是存儲信息的正確方法應用程序無法肯定地說。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM