Reputation: 133
I made this function to prevent duplicate usernames in my mysql database when registering. If it returns false then the name can be made:
public function nameTaken($username){
$statement = $this->pdo->prepare('SELECT count(*) FROM users WHERE name = :name');
$statement->execute(array('name' => $username));
$res = $statement->fetch(PDO::FETCH_NUM);
$exists = array_pop($res);
if ($exists > 0) {
echo 'user already exists';
return;
} else {
//the name can be made
return false;
}
}
When I tested it, even when it echo'd that users already exist and didn't return false, the username from the post request were still inserted into my database. Here is my function to insert into my database :
public function insert($table, $parameters){
$sql = sprintf(
'insert into %s (%s) values (%s)',
$table,
implode(', ', array_keys($parameters)),
':' . implode(', :', array_keys($parameters))
);
try {
$statement = $this->pdo->prepare($sql);
$statement->execute($parameters);
} catch (Exception $e) {
die('something went wrong');
}
}
and here is my controller that gets the post requests to to register a name
<?php
$hash = password_hash($_POST['password'], PASSWORD_BCRYPT);
if(!$app['database']->nameTaken($_POST['username'])){
$app['database']->insert('users', [
'name' => $_POST['username'],
'password' => $hash
]);
};
Upvotes: 1
Views: 37
Reputation: 24405
You need to return true
when the username is taken, otherwise your if statement will match null and false:
if(!$app['database']->nameTaken($_POST['username'])){
return;
is the same as return null;
which is "falsy" (loosely equivalent to false).
Upvotes: 2