Php insert no value in primary key MySql - php

I am inserting values from a form in a MySql table. The problem is when I leave one input field empty (it is a primary key), the db does not complain that the primary key is empty and the row is added to the table with an empty space in the primary key column.
$this->vendor_name = empty($params['name'])? $params['name']:null;
So in my case name is empty and I am inserting a NULL in the primary key but there is no warning from the db.

you should make the primary key auto_increment and not null
try it
CREATE TABLE vendedor(
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html

Yes inserting a NULL value is the right way, but in the code there is a simple condition error, this is the solution:
!empty($params['name'])?$params['name']:null;

Probably you have multiple primary keys. In this case only your first primary key cannot be null and must be unique, the others not. So if you want to set your column only for unique values, you can add a unique index.
ALTER TABLE `your_table`
ADD UNIQUE INDEX (`column_name`);

Related

Primary key request in MySQL

I used this code however it showed that unrecognized alter operation and also that key is unrecognized.
ALTER TABLE `ecommerce`.`users` (id INT(11) NOT NULL, PRIMARY-KEY AUTO_INCREMENT);
The correct syntax is:
ALTER TABLE ecommerce.users add column id INT AUTO_INCREMENT PRIMARY KEY;
Here is a db<>fiddle.
EDIT:
I realize the OP might already have the column and want to replace the definition. That works with this syntax:
ALTER TABLE users modify column id INT AUTO_INCREMENT PRIMARY KEY;
Here is this db<>fiddle.
you can give primary while creating your table or after create table you can add primary key by alter table
while creating table
create table info(id int primary key,Name varchar(25),dept varchar(25));
create table info(id int,Name varchar(25),dept varchar(25),primary key(id));
after creating table
alter table info add primary key(id);

Cannot create MYSQL primary keys

I am trying to drop the existing primary keys and add two new primary primary keys in an existing database table using the following query:
ALTER TABLE `match_team_recruit` DROP PRIMARY KEY,
ADD PRIMARY KEY (`ind_stnum`, `team_send`);
However, I get the following error when running the query.
#1062 - Duplicate entry '183-0' for key 'PRIMARY'
Please see attached Image below:
Can anyone advise how I can solve this?
A primary key in MySQL has to follow these three rules.
A primary key must contain unique values. If the primary key consists of multiple columns, the combination of values in these columns must be unique.
A primary key column cannot contain NULL values. It means that you have to declare the primary key column with the NOT NULL attribute. If you don’t, MySQL will force the primary key column as NOT NULL implicitly.
A table has only one primary key.
Courtesy: Introduction to MySQL primary key
To fix your problem you should just add one Primary Key to your table. The Primary Key is used to distinguish Row's, therefor you can't have multiple Primary Key's in one table!

How to recreate id column? [duplicate]

I am trying to alter a table which has no primary key nor auto_increment column. I know how to add an primary key column but I was wondering if it's possible to insert data into the primary key column automatically (I already have 500 rows in DB and want to give them id but I don't want to do it manually). Any thoughts? Thanks a lot.
An ALTER TABLE statement adding the PRIMARY KEY column works correctly in my testing:
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
On a temporary table created for testing purposes, the above statement created the AUTO_INCREMENT id column and inserted auto-increment values for each existing row in the table, starting with 1.
suppose you don't have column for auto increment like id, no, then you can add using following query:
ALTER TABLE table_name ADD id int NOT NULL AUTO_INCREMENT primary key FIRST
If you've column, then alter to auto increment using following query:
ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY
For those like myself getting a Multiple primary key defined error try:
ALTER TABLE `myTable` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST NOT NULL;
On MySQL v5.5.31 this set the id column as the primary key for me and populated each row with an incrementing value.
In order to make the existing primary key as auto_increment, you may use:
ALTER TABLE table_name MODIFY id INT AUTO_INCREMENT;
Yes, something like this would do it, it might not be the best though. You might wanna make a backup:
$get_query = mysql_query("SELECT `any_field` FROM `your_table`");
$auto_increment_id = 1;
while($row = mysql_fetch_assoc($get_query))
{
$update_query = mysql_query("UPDATE `your_table` SET `auto_increment_id`=$auto_increment_id WHERE `any_field` = '".$row['any_field']."'");
$auto_increment_id++;
}
Notice that the the any_field you select must be the same when updating.
The easiest and quickest I find is this
ALTER TABLE mydb.mytable
ADD COLUMN mycolumnname INT NOT NULL AUTO_INCREMENT AFTER updated,
ADD UNIQUE INDEX mycolumnname_UNIQUE (mycolumname ASC);
I was able to adapt these instructions take a table with an existing non-increment primary key, and add an incrementing primary key to the table and create a new composite primary key with both the old and new keys as a composite primary key using the following code:
DROP TABLE IF EXISTS SAKAI_USER_ID_MAP;
CREATE TABLE SAKAI_USER_ID_MAP (
USER_ID VARCHAR (99) NOT NULL,
EID VARCHAR (255) NOT NULL,
PRIMARY KEY (USER_ID)
);
INSERT INTO SAKAI_USER_ID_MAP VALUES ('admin', 'admin');
INSERT INTO SAKAI_USER_ID_MAP VALUES ('postmaster', 'postmaster');
ALTER TABLE SAKAI_USER_ID_MAP
DROP PRIMARY KEY,
ADD _USER_ID INT AUTO_INCREMENT NOT NULL FIRST,
ADD PRIMARY KEY ( _USER_ID, USER_ID );
When this is done, the _USER_ID field exists and has all number values for the primary key exactly as you would expect. With the "DROP TABLE" at the top, you can run this over and over to experiment with variations.
What I have not been able to get working is the situation where there are incoming FOREIGN KEYs that already point at the USER_ID field. I get this message when I try to do a more complex example with an incoming foreign key from another table.
#1025 - Error on rename of './zap/#sql-da07_6d' to './zap/SAKAI_USER_ID_MAP' (errno: 150)
I am guessing that I need to tear down all foreign keys before doing the ALTER table and then rebuild them afterwards. But for now I wanted to share this solution to a more challenging version of the original question in case others ran into this situation.
Export your table, then empty your table, then add field as unique INT, then change it to AUTO_INCREMENT, then import your table again that you exported previously.
You can add a new Primary Key column to an existing table, which can have sequence numbers, using command:
ALTER TABLE mydb.mytable ADD pk_columnName INT IDENTITY
I was facing the same problem so what I did I dropped the field for the primary key then I recreated it and made sure that it is auto incremental . That worked for me . I hope it helps others
ALTER TABLE tableName MODIFY tableNameID MEDIUMINT NOT NULL AUTO_INCREMENT;
Here tableName is name of your table,
tableName is your column name which is primary has to be modified
MEDIUMINT is a data type of your existing primary key
AUTO_INCREMENT you have to add just auto_increment after not null
It will make that primary key auto_increment......
Hope this is helpful:)
Well, you have multiple ways to do this:
-if you don't have any data on your table, just drop it and create it again.
Dropping the existing field and creating it again like this
ALTER TABLE test DROP PRIMARY KEY, DROP test_id, ADD test_id int AUTO_INCREMENT NOT NULL FIRST, ADD PRIMARY KEY (test_id);
Or just modify it
ALTER TABLE test MODIFY test_id INT AUTO_INCREMENT NOT NULL, ADD PRIMARY KEY (test_id);
How to write PHP to ALTER the already existing field (name, in this example) to make it a primary key? W/o, of course, adding any additional 'id' fields to the table..
This a table currently created - Number of Records found: 4 name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
This an end result sought (TABLE DESCRIPTION) -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
Instead of getting this -
Number of Records found: 5
id int(11) NO PRI
name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
after trying..
$query = "ALTER TABLE racehorses ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id)";
how to get this? -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
i.e. INSERT/ADD.. etc. the primary key INTO the first field record (w/o adding an additional 'id' field, as stated earlier.
No existing primary key
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
;
Table already has an existing primary key'd column
(it will not delete the old primary key column)
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
CHANGE COLUMN `prev_column` `prev_column` VARCHAR(2000) NULL ,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`id`);
;
Note: column must be first for auto increment which is why the FIRST command.

How to make a primary key to auto increment in a database in php?

I have a database and i am putting data inside. I have one node called key , which is the primary key and other nodes. Now when i put data on my table , i put data in all the nodes except this key node. How do i make it automatically to increase from 0 when i have a new entry? If i run a script to put something in the database , i can see that the nodes have correctly all the data and the key takes the value 0. When i run my script again i get the error :
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY''
From what i understand , because i dont pass anything to this node , the database "thinks" i am passing again a 0 argument so i have the error. How can i fix it to auto increment every time i have a new entry?
You need to set the field as autoincrement. You would need to run an ALTER TABLE statement like this:
ALTER TABLE table_name
MODIFY `key` MEDIUMINT NOT NULL AUTO_INCREMENT
id MEDIUMINT NOT NULL AUTO_INCREMENT
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
Start it at 1, not 0.
So the first record is id number 1.
What database are you using?
in postgres you register a number sequence.
In my sql you just use AUTO_INCREMENT when specifying the column attributes
With MySQL, you would declare the table with the AUTO_INCREMENT keyword when defining your table to achieve this behavior
Example:
CREATE TABLE animals (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM;
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
When you INSERT data, you do not specify a value for the primary key. MySQL will automatically use the next available integer value for the key.
UPDATE
You can change this directly within PHP My Admin: go to the table in question and then
Operations->Table Options->Auto-Increment

How can I make a key pair primary?

I have table that doesn't need a specific field to be the primary key. I could add a auto-increment ID field, but it won't be used at all within database queries...
Can I make a UNIQUE KEY to be primary too?
the UNIQUE KEY consists of two fields paired together:
a VARCHAR(64) NOT NULL,
b VARCHAR(64) NOT NULL,
UNIQUE KEY uk_ab(a,b)
Sure (no need for UNIQUE KEY):
PRIMARY KEY (a, b)
Have a look at the documentation:
A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL declares them so implicitly (and silently). A table can have only one PRIMARY KEY. The name of a PRIMARY KEY is always PRIMARY, which thus cannot be used as the name for any other kind of index.
and
A PRIMARY KEY can be a multiple-column index. However, you cannot create a multiple-column index using the PRIMARY KEY key attribute in a column specification. Doing so only marks that single column as primary. You must use a separate PRIMARY KEY(index_col_name, ...) clause.
Not sure if this would work...
PRIMARY KEY uk_ab(a,b)
If your table already has a unique constraint, then you need to add primary key (ALTER TABLE [table_name] ADD CONSTRAINT [constraint_name] PRIMARY KEY (a,b)), and drop the existing unique constraint. Otherwise, you will have 2 unique indexes on the same columns.
If you create a new table, use PRIMARY KEY(a,b) instead of UNIQUE(a,b) as proposed by others.

Categories