My code works only for one value, for the first one, after I try to add a second user, he no longer defines duplicates sees one element of the array, I understand what I need somehow through the cycle, but I don’t understand how .;

$app->get('/addtodb', function () use($app) { $name = $app -> request()-> get('name'); // connecting to db $db = new dbconnect(); $query = "SELECT id FROM users WHERE name='$name'"; $res = mysql_query($query); $row = mysql_fetch_array($res); echo $row['name']; if (!empty($row['id'])) { echo 'error'; } else { $result = mysql_query("INSERT INTO users (name) VALUES ('$name')"); }; }); $app->run(); 
  • name = asdf '; Hello from sql-ing - - Evgeny Borisov
  • it is not clear what you meant - Egor Krotenko
  • What is the structure of the table? And yes, clearly a jamb in the verification code - Evgeny Borisov
  • CREATE TABLE IF NOT EXISTS users ( phone int (11) NOT NULL, name text NOT NULL, secondname text NOT NULL, pass text text NOT NULL, user_type int (11) NOT NULL, id int (11) NOT NULL AUTO_INCREMENT, KEY id ( id ), KEY id_2 ( id )) - Yegor Krotenko
  • He meant that you have a potential sql injection. Never substitute the values ​​of variables in the query text. Use bind variables; see bind_param. - Mike

1 answer 1

The cycle is not needed here. Judging by your source code, first and foremost, the value that is inserted into the query is not checked either. On how to do the right in the network a lot of texts. Examine the object approach to msqli, prepare, etc.

In addition, you did not provide the current version of the source structure of the table, or you were too wise to think when creating it - a pair of identical keys on id explicitly - brute force.

In general, it is easier to take and rewrite everything from scratch than to rule. The correct approach is to guarantee the uniqueness of the required fields at the database level. In this case, you can simply drop the values, if they conflict with unique keys - the base will not change, you can see the error code.

It seems that you are engaged in self-education. It's fine. In this case, it is imperative to understand what kind of request is being formed. I recommend in the current version to check what falls into the $query variable. It is possible that you will see an error.