How can you implement a check for the uniqueness of the input field:

database schema:

CREATE TABLE `humans` ( `id` int(11) NOT NULL auto_increment, `lastname` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, PRIMARY KEY (`id`) ); 

connection file to the config / db.php database:

 <?php $databaseHost = 'localhost'; $databaseName = 'simple'; $databaseUsername = 'root'; $databasePassword = ''; $mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName); ?> 

html form:

 <html> <head> <title>Добавление</title> </head> <body> <form action="add.php" method="post" name="form1"> <table width="25%" border="0"> <tr> <td>Фамилия</td> <td> <input type="text" name="lastName"> </td> </tr> <tr> <td>Имя</td> <td> <input type="text" name="name"> </td> </tr> <tr> <td>Отчество</td> <td> <input type="text" name="patronymic"> </td> </tr> </table> </form> </body> </html> 

And the script itself, on which the question:

 <html> <head> <title>Добавление ++</title> </head> <body> <?php include_once("./config/db.php"); if(isset($_POST['Submit'])) { $lastName = stripslashes(trim($_POST['lastName'])); $name = stripslashes(trim($_POST['name'])); // проверка на пустые поля if(empty($lastName) || empty($name) ) { if(empty($lastName)) { echo "<font color='red'>Заполните фамилию</font><br/>"; } if(empty($name)) { echo "<font color='red'>Заполните имя</font><br/>"; } //link to the previous page echo "<br/><a href='javascript:self.history.back();'>Назад</a>"; } else { // if all the fields are filled (not empty) //insert data to database $result = mysqli_query($mysqli, "INSERT INTO humans(lastname,name) VALUES('$lastName','$name')"); //display success message echo "<font color='green'>Успех"; echo "<br/><a href='index.php'>Результат</a>"; } } ?> </body> </html> 

How can I competently check for the fact that:

if the database already has such a name, do not add it, leave it as it is, and just overwrite the last name, do not check if it is there or not.

  • For the sake of interest, hammer in the field of the name or the last name of an apostrophe, for example, as in "d'artanyan" and see what happens. On the face of the SQL injection. Never substitute variable values ​​directly into a query. Use bind variables (see bind_param) - Mike
  • @Mike is all clear. I would like to see an example of how my code can be improved - spectre_it

2 answers 2

 if(isset($_POST['submit'])) 

{

 $err = array(); 

$ query = mysql_query ("SELECT COUNT (id) FROM users WHERE login = '". mysql_real_escape_string ($ _ POST [' login ']). "'");

 if(mysql_result($query, 0) > 0) { $err[] = "Пользователь с таким логином уже существует в базе данных"; } 

if (count ($ err) == 0)

 { 

$ login = $ _POST ['login']; $ sql = mysql_query ("INSERT INTO users (` login``) VALUES ('$ login') "); if ($ sql) {echo "data passed"; } else {echo "data not transmitted"; }

  //header("Location: login.php"); exit(); } else { print "<b>При регистрации произошли следующие ошибки:</b><br>"; foreach($err AS $error) { print $error."<br>"; } } 

}

  • enter your current data. and it is easier to write errors in an array as I showed, than in echo to write - Koly
  • Could you format, I can not understand anything - is this your implementation? - spectre_it
  • Yes, you can say so - Koly
  • you kind of asked? - Koly

The uniqueness of the fields is done at the database level. This will not allow even errors in the application to enter incorrect data in the database. Your table can be declared like this:

 CREATE TABLE `humans` ( `id` int(11) NOT NULL auto_increment, `lastname` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY (`name`) ); 

A unique key ensures that two identical names cannot appear in the database.

After that, change your SQL query to add some data:

 insert into humans(lastname, name) values('last','first') on duplicate key update lastname=values(lastname); 

It will execute exactly what you wanted: if there is no name in the database yet, then it will create a new record, and if it does, it will change the name in the already existing record.

  • thanks for the answer. and at the application level, how do I catch the event recorded in the database, or is already there, and the field is overwritten. I think the query returns either one or the other, right? show how to wrap an error handler? - spectre_it
  • one
    @ stas0k php.net/manual/ru/function.mysql-affected-rows.php Pay attention to the special comment in this article about "on duplicate" - Mike