How can the use of SQL queries improve the security and efficiency of user authentication processes in PHP scripts?

Using SQL queries can improve the security and efficiency of user authentication processes in PHP scripts by allowing for parameterized queries to prevent SQL injection attacks. Additionally, SQL queries can help in retrieving user credentials securely from the database and comparing them with the input provided by the user during the authentication process.

// Establish a 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);
}

// Prepare a SQL query to retrieve user credentials
$stmt = $conn->prepare("SELECT username, password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Execute the query
$stmt->execute();

// Bind the result variables
$stmt->bind_result($dbUsername, $dbPassword);

// Fetch the results
$stmt->fetch();

// Verify the user's password
if(password_verify($password, $dbPassword)) {
    // User authentication successful
} else {
    // User authentication failed
}

// Close the statement and connection
$stmt->close();
$conn->close();