I want to check if the username
already exists and throw an error message if exist, any tips how can I do it?
I\'ve already tried to search but only found mys
If you want to check if the username
is already used :
SELECT * FROM users WHERE username = :username
If you return one row : you throw your error, else you do your INSERT
So your code should look like this :
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql_check = "SELECT * FROM users WHERE username = :username";
$test = $pdo->prepare($sql_check);
$test->bindParam(':username', $username);
$test->execute;
Now here is two solution to check if you have one row :
if($test->rowCount() > 0) {
// error
}
or
$user = $test->fetch();
if (!empty($user)) {
// error
}
And now if you don't have error, do you insert :
else {
//$password = md5($password);
$sql = "INSERT INTO users (username,password,role) values(?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($username,$password,$role));
Database::disconnect();
header("Location: index.php");
}
}