如何使用PHP创建正确的mySQL CREATE TABLE语句

时间:2016-08-11 22:40:21

标签: php mysql

我正在尝试使用PHP将此查询插入mySQL数据库,但我一直收到此错误:

  

无法创建表ecommerce1orders(错误:150“外键约束形成错误”)

我如何正确地形成这个陈述?

$query = "CREATE TABLE `orders` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`users_id` INT UNSIGNED NOT NULL,
`transaction_id` VARCHAR(45) NOT NULL,
`payment_status` VARCHAR(45) NOT NULL,
`payment_amount` INT UNSIGNED NOT NULL,
`date_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `date_created` (`date_created` ASC),
INDEX `transaction_id` (`transaction_id` ASC),
CONSTRAINT `fk_orders_users1` FOREIGN KEY (`id`)
  REFERENCES `users` (`id`)
  ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE = InnoDB DEFAULT CHARSET=utf8";

echo "<p>************</p>";
echo $query;
echo "<p>************</p>";

if($mysqli->query($query) === TRUE) {
echo "<p>Database table orders created</p>";
}
else {
echo "<p>Error: </p>" . mysqli_error($mysqli);
}

2 个答案:

答案 0 :(得分:1)

情况并非如此。如果您收到此错误,则意味着关键列按定义不匹配(最可能是数据类型不匹配)。如果我尝试下面的示例代码,它工作正常。请参阅此小提琴演示http://sqlfiddle.com/#!9/6a15c

CREATE TABLE `users`(`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY);

CREATE TABLE `orders` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`users_id` INT UNSIGNED NOT NULL,
`transaction_id` VARCHAR(45) NOT NULL,
`payment_status` VARCHAR(45) NOT NULL,
`payment_amount` INT UNSIGNED NOT NULL,
`date_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `date_created` (`date_created` ASC),
INDEX `transaction_id` (`transaction_id` ASC),
CONSTRAINT `fk_orders_users1` FOREIGN KEY (`id`)
  REFERENCES `users` (`id`)
  ON DELETE NO ACTION ON UPDATE NO ACTION

答案 1 :(得分:0)

试试这个:

CREATE TABLE `users`(`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY);

CREATE TABLE `orders` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`users_id` INT UNSIGNED NOT NULL,
`transaction_id` VARCHAR(45) NOT NULL,
`payment_status` VARCHAR(45) NOT NULL,
`payment_amount` INT UNSIGNED NOT NULL,
`date_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `date_created` (`date_created` ASC),
INDEX `transaction_id` (`transaction_id` ASC),
CONSTRAINT `fk_orders_users1` FOREIGN KEY (`id`)
  REFERENCES `users` (`id`)
  ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE = InnoDB DEFAULT char SET utf8;