使用PHP PDO查询执行mySQL查询。查询由foreach()输入的大量信息组成;所以我已经回应了sql查询。问题出在这里,但我看不到它。
这是$sql
CREATE TABLE IF NOT EXISTS `page` (
`page_ID` INT AUTO_INCREMENT NOT NULL,
`url` varchar(200) NOT NULL,
`title` varchar(200),
`subtitle` TEXT,
`content` TEXT,
`parent` varchar(10),
`privacy` varchar(1),
`status` varchar(1),
`creation` varchar(30)
) CHARACTER SET utf8 COLLATE utf8_general_ci;
FYI查询执行如下:
function createdbtable($table,$fields){
global $fsdbh;
$sql = "CREATE TABLE IF NOT EXISTS `$table` (";
foreach($fields as $field => $type){ $sql.= "`$field` $type,"; }
$sql = rtrim($sql,',');
$sql .= ") CHARACTER SET utf8 COLLATE utf8_general_ci"; return $sql;
if($fsdbh->exec($sql) !== false) { return 1; }
}
这是错误:
#1075 - 表定义不正确;只能有一个自动列,必须将其定义为键
答案 0 :(得分:10)
您忘记了主键:
CREATE TABLE IF NOT EXISTS `page` (
`page_ID` INT AUTO_INCREMENT NOT NULL,
`url` varchar(200) NOT NULL,
`title` varchar(200),
`subtitle` TEXT,
`content` TEXT,
`parent` varchar(10),
`privacy` varchar(1),
`status` varchar(1),
`creation` varchar(30),
PRIMARY KEY (`page_ID`))
CHARACTER SET utf8 COLLATE utf8_general_ci
错误非常明确:
架构创建失败:表定义不正确;只能有一个自动列,必须将其定义为键
您必须将自动增量键指定为键。
修改强>
对于PHP代码,我将会这样:
function createdbtable($table,$fields)
{
global $fsdbh;
$sql = "CREATE TABLE IF NOT EXISTS `$table` (";
$pk = '';
foreach($fields as $field => $type)
{
$sql.= "`$field` $type,";
if (preg_match('/AUTO_INCREMENT/i', $type))
{
$pk = $field;
}
}
$sql = rtrim($sql,',') . ' PRIMARY KEY (`'.$pk.'`)';
$sql .= ") CHARACTER SET utf8 COLLATE utf8_general_ci"; return $sql;
if($fsdbh->exec($sql) !== false) { return 1; }
}