Paste the names into the table, if they were not already

I am trying to create an application that allows users to send names to be added to the db table (runningList). Before adding the name tho, I would like to check firstname and lastname against another table (controlList). It must exist in (controlList) or the response name is invalid. If the name is valid, I would like to check firstname and lastname against (runningList) to make sure it no longer exists. If not, insert the first and last name. If it is, the response name is already in use.

Below is the code that worked before I tried to add the test to the controlList list, I somehow broke it, trying to add an extra step.

if (mysql_num_rows(mysql_query('SELECT * FROM runninglist WHERE firstname=\'' .$firstname . '\' AND lastname=\'' . $lastname . '\' LIMIT 1')) == 0) { $sql="INSERT INTO runninglist (firstname, lastname) VALUES ('$_POST[firstname]','$_POST[lastname]')"; } else { echo "This name has been used."; } 

Any suggestion?

+4
source share
2 answers

Create a "unique" index (first name, last name).

Then, when the insert starts, it will fail. Just ignore the error (or do other things)


Edit: quote from manual:

A UNIQUE index creates a constraint, so all values ​​in the index must be different. An error has occurred if you try to add a new row using the key value that matches the existing row.

+3
source

The best way is to create an index for both columns: firstname and lastname

 ALTER TABLE youtableName ADD UNIQUE uniqueName (firstname,lastname) 

Therefore, an error already exists when trying to insert a name.

+3
source

Source: https://habr.com/ru/post/1433696/


All Articles