Everything important about the DB @Dharman have already said and this code is based on Dharman's code but with another approach for doing the same thing with the actual error messages.
My approach requires that the input-field's name is the same name as the name of the db-fields, e.g. <input name="email>
requires email field in db, <input name="username">
requires username field in db etc.
If you would like to show all of the messages:
$stmt = $con->prepare('SELECT username, email FROM accounts
WHERE username = ? OR email = ?');
$stmt->bind_param('ss', $_POST['username'], $_POST['email']);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
$errors = array_intersect($_POST,$row);
foreach($errors as $key=>$item) {
echo "$key already exists, please choose another<br>";
}
}
If you just want to show one of the messages (the first), you could simply do a break in the loop...
$stmt = $con->prepare('SELECT username, email FROM accounts
WHERE username = ? OR email = ?');
$stmt->bind_param('ss', $_POST['username'], $_POST['email']);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
$errors = array_intersect($_POST,$row);
foreach($errors as $key=>$item) {
echo "$key already exists, please choose another<br>";
break;
}
}
...or just fetching the first key in the array $errors:
$stmt = $con->prepare('SELECT username, email FROM accounts
WHERE username = ? OR email = ?');
$stmt->bind_param('ss', $_POST['username'], $_POST['email']);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
$errors = array_intersect($_POST,$row);
if (!empty($errors)) {
echo array_keys($errors)[0] . " already exists, please choose another";
}
}