What are some common methods for checking if a user exists in a MySQL table using PHP and HTML forms?

When working with PHP and MySQL, it is common to need to check if a user exists in a database table before performing certain actions. One common method to achieve this is by using a SELECT query to retrieve the user's information based on a provided username or email, and then checking if any rows are returned. If rows are returned, it means the user exists in the table.

<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check if the connection was successful
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Get the username or email from the HTML form
$username = $_POST['username'];

// Query to check if user exists
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($connection, $query);

// Check if any rows were returned
if (mysqli_num_rows($result) > 0) {
    echo "User exists in the database.";
} else {
    echo "User does not exist in the database.";
}

// Close the connection
mysqli_close($connection);
?>