mysql建多个表_SQL一次创建多个表
I need to create multiple tables at once. Im having a hard time figuring out the correct method for accomplishing this. Currently my script looks like this:private function buildDB() {$sql = <<C

I need to create multiple tables at once. Im having a hard time figuring out the correct method for accomplishing this. Currently my script looks like this:
private function buildDB() {
$sql = <<
CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
Obviously, this doesn't work and no tables are created. Is there a simple way for creating multiple tables at once?
解决方案
MySQL is getting confused because you're not delimiting your queries. Add a semicolon after the first CREATE statement:
private function buildDB() {
$sql = <<
CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
);
CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
Also, make sure MySQL_QUERY is at the beginning of the line with no other characters, except maybe a semicolon, as per the Heredoc documentation.
Seeing as the above doesn't appear to work, give this code a try:
private function buildDB() {
$sql1 = "CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100))";
$sql2 = "CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100))";
MySQL_QUERY;
return mysql_query($sql1) && mysql_query($sql2);
}
You could use mysqli_multi_query() (the MySQL version doesn't exist), but you'd have to use MySQLi then. The above code returns the logical AND of the two queries, so you still get a 0 returned if one fails.
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)