Avoid inserting into a table using PHP / SQL if this record already exists

2

When I precede in my " Submit " I execute an insert " Insert " that saves a series of records " X[i+] ":

id,_Nombre,__fecha

a

id,_Nombre,__fecha
1__Juan_____22/12/2000
2__Fulano___22/12/2000
3__Aldo_____22/12/2000

I wish that if I press again my submit to save the current record of that month, I will not allow it if these already exist.

My line of insertions:

include "conn.php"; ($conn)
$query = "INSERT INTO datosp (nombres,fecha) SELECT ('$nombres',CURRENT_TIMESTAMP) FROM usuarios;
sqlsrv_query($conn, $query) or die (print_r( sqlsrv_errors(), true));

Thank you very much.

    
asked by claus 19.07.2018 в 17:13
source

1 answer

2

You can control the avoidance of entering duplicate records directly from the database manager:

If for example you are just going to create your table, you do it like this

edad INT UNIQUE NOT NULL

When using the attribute UNIQUE , it will be the engine itself that verifies when you try to register, if that record already exists; in the affirmative case this CONSTRAINT that asks for unique values will be activated and will return an error that says more or less like this:

  

1062 - Duplicate entry '' for ........

What happens if I already have the column created?

You should do the following

ALTER TABLE usuarios ADD UNIQUE edad_unique (edad);

If you are going to declare as unique to different columns of your table you can achieve it in the following way

ALTER TABLE usuarios ADD UNIQUE datos_unique (edad, nombre, email);

CLARIFICATIONS

  • With the statement ALTER , I modify some element of the original structure of the table
  • With the operator ADD I indicate that I am going to add something new to the declaration of that column
  • when I add UNIQUE I indicate that the values or columns that I am going to declare later will be unique
  • answered by 19.07.2018 / 22:35
    source