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
Two solutions:
You could make the username field unique, this way, MYSQL would throw an error if you try to insert a line with an existing username.
$sql = "INSERT INTO users (username,password,role) values(?, ?, ?)";
$q = $pdo->prepare($sql);
$result = $q->execute(array($username,$password,$role));
if(!$result) {
// print out your error message
}
Otherwise, make a select with the wanted username and see if a row is returned (= already used) or not (=available).
$sql = "SELECT COUNT(*) as count FROM users WHERE username = ?";
$q = $pdo->prepare($sql);
$q->execute(array($username));
$result = $q->fetchAll();
// test result, if 1 > print error, etc