Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 我可以使用PDO参数化语句创建MYSQL表吗?_Php_Mysql_Pdo - Fatal编程技术网

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

Php 我可以使用PDO参数化语句创建MYSQL表吗?,php,mysql,pdo,Php,Mysql,Pdo,我希望使用PHP和PDO创建一个MySQL表。我还希望参数化表名。我已经尝试实现了这一点,下面显示了错误代码 class databaseaccess { public $hostname = 'localhost'; public $username = 'root'; public $password = 'root'; private $db = null; public $rows; public function __construc

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

    }
}
上述代码的输出如下:

数组
(
[0] => 42000
[1] => 1064
[2] =>您的SQL语法有错误;请检查与您的MySQL服务器版本对应的手册,以了解在第2行的“exampletablename”(id INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(id),username VARCHAR(20))EN)附近使用的正确语法
)
示例表名

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

您不能在准备好的语句中使用占位符作为标识符(列/表/数据库/函数名等)。只能对值使用它们

CREATE TABLE noteshareproject.:title
//                            ^^^^^^ this will not work
您必须手动清理
$title
,以便可以在字符串中直接使用它

还请注意,无法准备诸如
CREATE TABLE
之类的语句,因此使用
prepare()
没有任何意义。你也可以用或


我还想知道,您想这样做是否表明数据库设计糟糕——要求多个结构相同的表不太可能是存储信息的正确方式,虽然在不了解更多应用程序的情况下,无法确定。

您是否手动尝试过该查询?谢谢。我会考虑你的数据库设计技巧。