简体   繁体   中英

Simple INSERT query creates 2 records instead of one

You've got a simple table, a simple INSERT query and a quite weird result. Instead of a single empty query, the second mysql_query call creates 2 empty records. Why?

mysql_query("
    CREATE TABLE `users` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `email` varchar(255) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8");

mysql_query("INSERT INTO `users` SET `users`.`id` = NULL");

Note: Running the query in phpMyAdmin gives the expected result - creates a single record.

Edit:

Adding the following mysql_query call to the beginning of the snippet fixes it.

mysql_query("DROP TABLE `users`");

Edit:

Turned out the problem is related to mod_rewrite ( related question ).

As I understand you run this script twice.

The first time script does:

  1. Create table.
  2. Insert row

The secont time:

  1. Tries to create table, but you get an error because table already exists, and nothing happens
  2. Insert second row

Try to add this line to check errors - 'echo mysql_error()."\\n";'. For example -

mysql_query("
    CREATE TABLE `users` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `email` varchar(255) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8");

echo mysql_error()."\n";

尝试使用INSERT INTO users (id) VALUES (NULL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM