MySQL

How to Check if Username Already Exists in Database using PHP MySQL

In this tutorial, we are going to see different methods to check if the username already exists in the database with PHP and MySQL. If you are a “newbie” you should know how to connect to a MySQL database before using the code below. You cannot check if the username already exists in the database if you are not logged in to it.
 

 

Method 1: How to Check if Username Already Exists in Database using PDO

To check if a particular value exists in the database, all you need to do is run a SELECT query.

<?php
//get username from form
$username = $_POST['username'];
//prepare the statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username=?");
//execute the statement
$stmt->execute([$username]); 
//fetch result
$user = $stmt->fetch();

if ($user) {
    // username already exists
} else {
    // username does not exist
} 
?>

 

Method 2: How to Check if Username Already Exists in Database using MySQLi

To check if a particular value exists in the database, all you need to do is run a SELECT query.

<?php

$select = mysqli_query($conn, "SELECT * FROM users WHERE username = '".$_POST['username']."'");
if(mysqli_num_rows($select)) {
    exit('This username already exists');
}
?>
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *