我可以使用PDO参数化语句创建MYSQL表吗? [英] Can I create a MYSQL table using a PDO parameterized statement?
问题描述
我希望使用PHP和PDO创建一个MySQL表.我也希望参数化表名.我已经尝试过实现这一点,下面显示了有错误的代码.
I wish to create a MySQL table using PHP and PDO. I also wish to parameterize the table name. I have already attempted to implement this and the code, with errors, is shown below.
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实现中做错了什么?
What have I done wrong in my MySQL syntax or PDO implementation?
推荐答案
您不能在准备好的语句中使用占位符作为标识符(列/表/数据库/函数名称等).您只能将它们用作值.
You cannot use placeholders in prepared statements for identifiers (column/table/database/function names etc). You can only use them for values.
CREATE TABLE noteshareproject.:title
// ^^^^^^ this will not work
您将必须手动清理$title
,因此如果要执行此操作,可以直接在字符串中使用它.
You will have to manually sanitise $title
so it can be used directly in the string if you want to do this.
还请注意,无法准备诸如CREATE TABLE
之类的 DDL 语句,因此存在使用prepare()
没有意义.您最好只使用 query()
或
Note also that a DDL statement such as CREATE TABLE
cannot be prepared, so there is no point in using prepare()
. You might as well just use query()
or exec()
.
我也确实想知道您是否真的想这样做表明数据库设计不佳-尽管不知道,但对多个具有相同结构的表的要求不太可能是存储信息的正确方法关于您的应用程序的更多信息,无法确定.
I do also wonder if the fact that you want to do this at all is an indicator of poor database design - it is unlikely that a requirement for multiple tables of identical structure is a proper way to store your information, although without knowing more about your application it is impossible to say for sure.
这篇关于我可以使用PDO参数化语句创建MYSQL表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!