Stefano Maglione
Stefano Maglione

Reputation: 4150

Php insert no value in primary key MySql

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.

Upvotes: 0

Views: 420

Answers (3)

DrKey
DrKey

Reputation: 3495

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`);

Upvotes: 0

Stefano Maglione
Stefano Maglione

Reputation: 4150

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;

Upvotes: 0

Bob White
Bob White

Reputation: 733

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

Upvotes: 1

Related Questions