In this tutorial we will discover different method to check if the username already exists in the database with PHP and MySQL.
Method 1: Using PDO
To check whether a particular value exists in the database, you just need to execute a SELECT query, extract a row, and check if something has been extracted.
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $username = $_POST['username']; $stmt = $pdo->prepare("SELECT * FROM users WHERE username=?"); $stmt->execute([$username]); $user = $stmt->fetch(); if ($user) { // the username already exists } else { // the username does not exist } |
Method 2: Using MySQLi
1 2 3 4 5 6 7 | <?php $select = mysqli_query($conn, "SELECT * FROM users WHERE username = '".$_POST['username']."'"); if(mysqli_num_rows($select)) { exit('This username already exists'); } |