Ho can I check the database first if a user exists then use a insert statement if it does not. The code currently only executes the select statement.
<?php
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
if (mysqli_query($dbconn, $query_check_user)) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
?>
mysqli_queryreturnsfalseonly on failure, not just because it returns an empty set.SELECTis bad because it's not accurate information. By the time you're done checking, another process can insert that record and you can end up with 2 records that are the same. To fight this problem, we useuniqueconstraints, we simply insert and if database reportsduplicate key errorthen we know a record exists.(username, is_deleted)or hash(username, is_deleted)and save that as unique constraint.