gpt4 book ai didi

PHP PDO mySQL 查询如果不存在则创建表

转载 作者:可可西里 更新时间:2023-11-01 07:48:19 25 4
gpt4 key购买 nike

使用 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;

仅供引用,查询是这样执行的:

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 - Incorrect table definition; there can be only one auto column and it must be defined as a key

最佳答案

您忘记了主键:

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

错误非常明显:

Schema Creation Failed: Incorrect table definition; there can be only one auto column and it must be defined as a key

您必须指定自增键作为键。

编辑:

对于 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";
if($fsdbh->exec($sql) !== false) { return 1; }
}

关于PHP PDO mySQL 查询如果不存在则创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12095285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com