Enter data using Php to MySql in multiuser

1

I would like to enter data at Mysql , I tried to use the following sentence:

$query="SELECT MAX(cod_unico)+1 ultimo FROM $tabla";

but this does not allow it because it only brings you the last id but at the time of entry there can be duplicity or errors for not allowing duplicity.

    
asked by Rsistemas 02.07.2018 в 09:00
source

1 answer

0

If you want to avoid that the ID of what you are inserting matches existing records, in the database you can use AUTO_INCREMENT when defining your table. For example:

CREATE TABLE usuarios (
  id int AUTO_INCREMENT,
  nombre varchar(256) NOT NULL,
  apellidos varchar(256) NOT NULL,
  PRIMARY KEY (id),
);

In this way when you insert a new record you just have to specify the fields nombre and apellidos , the ID would be generated automatically.

If you can not use AUTO_INCREMENT you would have to do a SELECT MAX(id) FROM usuarios to recover the id bigger than you have and then when inserting add +1 to the value of said id. Although this last option would not be highly recommended if many users are going to use the application simultaneously.

    
answered by 02.07.2018 в 09:31