This question already has answers here:
MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'
(9 answers)
Closed 6 years ago.
I am building a CRUD app in PHP & MySql. It uses two tables, called users and medical_records:
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(1024) NOT NULL,
`validation_code` text NOT NULL,
`active` tinyint(1) NOT NULL,
`telefon` varchar(255) DEFAULT NULL,
`oras` varchar(255) DEFAULT NULL,
`adresa` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE medical_records (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`fo` VARCHAR(255),
`condition` VARCHAR(255),
`transfer` VARCHAR(255),
`memo` text(1024),
`body_temperature` VARCHAR(255),
PRIMARY KEY (`id`),
CONSTRAINT FK_medical_records_1
FOREIGN KEY (user_id) REFERENCES users(id)
ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
The "business logic" of these tables is: every user has one (only one) medical record.
I used and tested the application when it only had the users table. Register and login worked fine, so I conclude that the problem's source can't be the application's (PHP) code.
I later doped the users table and added the 2 fresh tables the application now uses (users and medical_records).
At this moment whenever I try to register a second user, I get the error:
QUERY FAILED: Duplicate entry '0' for key 'PRIMARY'
This happens despite the fact that both tables have auto incremented primary keys. What could be the explanation of that?
the id in the users table is not set to AUTO_INCREMENT. that's why this happens.
Related
I am creating a User Management System and need your advice.
3 entities:
Users
Firm
Group
Each user will belong to one Firm.
Some users (not all) may belong to Group.
Group is a combination of Firms. (E.g. 3 firms in a group)
The data will be displayed according to user's firm or group, if a user belongs to firm (but not group), then firm level data will be displayed. And if the user belong to group then group level data (e.g. 3 firms' data) will be displayed.
Is my below mentioned approach correct for this purpose:
CREATE TABLE `user_account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firm` varchar(45) DEFAULT NULL, # each user belong to a client firm
`group` varchar(45) DEFAULT NULL, # some users may belong to client group
`name` varchar(45) DEFAULT NULL,
`username` varchar(15) NOT NULL, # USER ID
`password` varchar(255) NOT NULL,
`email` varchar(40) NOT NULL,
`account_creation_date` datetime DEFAULT NULL,
`active` tinyint(1) DEFAULT '1',
`token_code` varchar(255) DEFAULT NULL, # for password recovery
`token_creation_date` datetime DEFAULT NULL, # for password recovery
PRIMARY KEY (`id`),
UNIQUE KEY `username_UNIQUE` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `permission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL, # FOREIGN KEY user_account.user_name
`association` varchar(45) DEFAULT NULL, # Firm or Group
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm setting up a new web service, and need some help with organizing the data in my application. My application's written in PHP, and I plan to store all user data in using MySQL Databases.
I will have a bunch of users, and each of those users will have a bunch of data that is tied to their account. It's a note taking application, and so, naturally, for every user, I need to keep track of the number of notes, and the content of each of those notes.
How do I go about structuring this and translating this into MySQL tables? I know I have to do something that revolves around linked (related) tables, but can't seem to pinpoint it.
I have 10x1GB databases.
Have the following tables (you can choose your own names);
tbl_users
int(4) userid (PRIMARY)
varchar(128) firstname
varchar(128) lastname
tbl_notes
int(8) noteid (PRIMARY)
int(4) userid
text notecontent
As you can see, userid is the relation between the two tables (1 to many in this case).
See Database normalization from Wikipedia
Try following queries to create your tables:
Users:
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`password` varchar(255) DEFAULT NULL,
`email_address` varchar(96) NOT NULL,
`firstname` varchar(32) NOT NULL,
`lastname` varchar(32) NOT NULL,
`birth_date` datetime DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`street` varchar(16) NOT NULL,
`address` varchar(64) NOT NULL,
`city` varchar(32) NOT NULL,
`state` varchar(32) DEFAULT NULL,
`country` int(11) NOT NULL DEFAULT '0',
`postcode` varchar(10) NOT NULL,
`status` int(1) DEFAULT '0',
`created` datetime DEFAULT NULL,
`updated` datetime DEFAULT NULL
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Notes:
CREATE TABLE IF NOT EXISTS `notes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
`date_added` datetime NOT NULL,
`date_sent` datetime DEFAULT NULL,
`status` int(1) DEFAULT NULL,
`locked` int(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Hi any one please help i have a contact table in which i can Insert,Delete,Modify database using PHP web pages....but only current changes will be updated to database. what i want is how i can maintain history of database...
Is there any tutorial for this using (PHP/MYSQL).
I tried creating version of MySQL table for patient... how to proceed further.
CREATE TABLE IF NOT EXISTS `contact` (
`name` varchar(30) NOT NULL,
`phone` varchar(12) NOT NULL,
`mobile` varchar(12) NOT NULL,
`email` varchar(30) NOT NULL,
`address` text NOT NULL,
`conid` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`conid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; # MySQL returned an empty result set (i.e. zero rows).
CREATE TABLE IF NOT EXISTS `contactversion` (
`name` varchar(30) NOT NULL,
`phone` varchar(12) NOT NULL,
`mobile` varchar(12) NOT NULL,
`email` varchar(30) NOT NULL,
`address` text NOT NULL,
`conid` int(11) NOT NULL,
`revision_id` int(11) AUTO_INCREMENT,
type ENUM('INSERT', 'UPDATE', 'DELETE') NOT NULL,
`change_time` DEFAULT current_timestamp,
PRIMARY KEY (`revision_id`)
);
what to do next....
When running the queries to contact, just simply run this right before to take the current contact and copy it in your revision table...
"INSERT INTO
contactversion (name,phone,mobile,email,address,conid,type)
SELECT
name,phone,mobile,email,address,conid,'".$type."' as type
FROM contact
WHERE conid='".$conid."'"
Both tables will require to be identical, with contactversion having type and change_time as additionnal last columns.
It is obvious that this query should be ran before UPDATE and DELETE of the contact table, but after an INSERT. If you are updating multiple contacts with another where clause than the conid, you'll want to consider building the where statement in a variable to use it inside the INSERT's SELECT and the UPDATE/DELETE
While creating contactversions table make sure conid should not be primary key and auto incremented. I hope that is causing the problem.
This is my first post and I can't seem to find the answer anywhere....
I have a database that has multiple companies,each company has multiple locations.
I'm running into problems trying to define the contacts. Some contacts need to be global and available
at any location....some contacts only need to exist for one location. In the contact_info table below
we specify the visibility of the contact (company or location). However the location needs to choose its primary contact.
That leaves a FK from contact -> location and from location -> contact.
I know there is another table involved but I can't seem to conceptualize it.
CREATE TABLE `company_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`));
CREATE TABLE `location_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`company_info` INT NOT NULL DEFAULT -1,
`name` VARCHAR(100) NOT NULL DEFAULT '',
`primary_contact_id` INT NOT NULL DEFAULT -1,
PRIMARY KEY(`id`),
UNIQUE KEY(`company_id`,`name`),
FOREIGN KEY (company_id) REFERENCES company_info(id)
FOREIGN KEY (primary_contact_id) REFERENCES contact_info(id));
CREATE TABLE `contact_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`company_id` INT
`location_id` INT,
`type` ENUM('Company','Location') NOT NULL DEFAULT 'Company',
`first_name` VARCHAR(50) NOT NULL DEFAULT '',
`last_name` VARCHAR(50) NOT NULL DEFAULT '',
PRIMARY KEY(`id`),
UNIQUE KEY(`id`,`company_id`,`location_id`),
FOREIGN KEY (location_id) REFERENCES location_info(id),
FOREIGN KEY (company_id) REFERENCES company_info(id)
The most effective way would be splitting it up so that there's a table for your companies, a table with your users, and a table solely for the purpose of storing all connections (i.e. EntryID, UserID, CompanyID). This way you'll be able to easily load them afterwards.
I have four tables, namely
countries,states,cities,areas
which will be the best feasible solution for my database table
Method A :
CREATE TABLE IF NOT EXISTS `countries` (
`id` int(11) auto_increment NOT NULL,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `states` (
`id` int(11) auto_increment NOT NULL,
`name` varchar(50) NOT NULL,
`country_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `cities` (
`id` int(11) auto_increment NOT NULL,
`name` varchar(50) NOT NULL,
`state_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `areas` (
`id` int(11) auto_increment NOT NULL,
`name` varchar(50) NOT NULL,
`zipcode` int(11) NOT NULL,
`city_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
or Method B :
CREATE TABLE IF NOT EXISTS `countries` (
`id` int(11) auto_increment NOT NULL,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `states` (
`id` int(11) auto_increment NOT NULL,
`name` varchar(50) NOT NULL,
`country_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `cities` (
`id` int(11) auto_increment NOT NULL,
`name` varchar(50) NOT NULL,
`state_id` int(11) NOT NULL,
`country_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `areas` (
`id` int(11) auto_increment NOT NULL,
`name` varchar(50) NOT NULL,
`zipcode` int(11) NOT NULL,
`city_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`country_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Thank you..
The first is less likely to have problems with synchronization.
The second will offer better performance through denormalization.
Possible related thread: What is a good way to denormalize a mysql database?
The second version will lead to major headaches if mismatched data is entered. Take the following sample data:
countries: Canada, USA
states: Saskatchewan, Michigan
cities: Saskatoon, Detroit
zipcode: 90210 (california)
insert into area (...) ('Canada', 'Michigan', 'Saskatoon', 90210)
all individually valid, but the entire record is utterly wrong. Yet, by your design, it's supposed to be valid.
It probably depends on what queries you are going to run on those tables. In general, A is normalized whereas B is not (A will use less space).
I would start with Method A, but if it turns out performance requires the additional columns further down the chain, I'd add them only as needed.
Just be sure to make your _id columns indexes.
I prefer Method A at first glance, but without knowing specifics about what you want the relationships and constraints to be, it's impossible to say categorically that one is "better" than the other. Follow your application's functional requirements.
Congratulations on looking towards a normalised approach: it's nice to see!
I personally would choose the first one [Method A]. If you know, for example, the city ID of an area, then you automatically know the state ID and the country ID. While the second one may be a bit more convenient, you may run into issues down the line if say, a city moved to a different state.
It's always best to start with the normalized form. I would only suggest Method B if you had your RDBMS automatically managing cached column updates. For example, if you mistakenly placed Los Angeles in Michigan, you would need to update multiple locations (unless you had triggers that would update cascading pieces of information in denormalized tables). But without triggers, Method A is without a doubt the best form.
This is assuming of course that your constraints match the ones implicitly dictated by common interpretation when viewing Method A's definition.