我可以使用PDO参数化语句创建MYSQL表吗?

Jon*_*ord 2 php mysql pdo

我希望使用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;

    }
}
Run Code Online (Sandbox Code Playgroud)

上面代码的输出如下:

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
Run Code Online (Sandbox Code Playgroud)

我在MySQL语法或PDO实现中做错了什么?

Dav*_*dom 6

您不能在预准备语句中使用占位符来标识符(列/表/数据库/函数名称等).您只能将它们用于值.

CREATE TABLE noteshareproject.:title
//                            ^^^^^^ this will not work
Run Code Online (Sandbox Code Playgroud)

$title如果要执行此操作,则必须手动清理,以便可以直接在字符串中使用.

另请注意,DDL语句如CREATE TABLE无法编写,因此没有必要使用prepare().你也可以使用query()exec().

我也想知道你想要这样做的事实是否是数据库设计不佳的一个指标 - 虽然不知道更多关于你的信息,但是对于具有相同结构的多个表的要求是不太可能是存储信息的正确方法.申请是不可能肯定的.