What is the correct SQL query syntax to check if a user already exists in the database using PHP and MySQL?
When checking if a user already exists in the database using PHP and MySQL, you can use a SELECT query to search for the user based on a unique identifier, such as their username or email. If the query returns a result, then the user already exists in the database. You can then use the mysqli_num_rows function to check if any rows were returned by the query.
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if user exists
$username = "example_user";
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "User already exists in the database.";
} else {
echo "User does not exist in the database.";
}
$conn->close();
?>