HTML PHP - How to check if the username already existed


The script is already working fine but I want to insert a command that allows only if the username is not yet used.

if (isset($_POST['submit'])) {
    $firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
    $lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
    $position = htmlentities($_POST['position'], ENT_QUOTES);
    $username = htmlentities($_POST['username'], ENT_QUOTES);
    $password = htmlentities($_POST['password_two'], ENT_QUOTES);
    $uniqid = uniqid('', true);
    if ( $firstname == '' || $lastname == '' ||  $position == '' || $username == '' || $password == '') {
        $error = 'ERROR: Please fill in all required fields!';
        renderForm($error, $firstname, $lastname, $position, $username, $password);

    } else {
        if ($stmt = $connection->prepare("INSERT INTO employee (uniqid, firstname, lastname, position, username, password) VALUES (?, ?, ?, ?, ?, ?)")) {
            $stmt->bind_param("ssssss", $uniqid, $firstname, $lastname, $position, $username, $password);
        } else {
            echo "ERROR: Could not prepare SQL statement.";
        header("Location: regemployee.php");
} else {



Make username unique on the DB, then when you try to insert the same username in to the DB again, the insert will through an error.

Alternatively you could do aSELECT * FROM employee WHERE username = ? and check if results is > 0.

Then you would know it exists already.




Do anotherSELECT query which checks if the submittedusername already exist:

$stmt = $connection->prepare("SELECT * FROM employee WHERE username = ?");
$stmt->bind_param("s", $username);

Then get the number of results:

$noofres = $stmt->num_rows;

Then, create a condition that if it yet doesn't exist, it will do the insert query:

if($noofres == 0){


} else {

    echo 'Username already taken.';


People are also looking for solutions to the problem: apache - HTTPS and Remove index.php on CodeIgniter


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.