How can SQL-Injections be prevented in PHP scripts, especially in login functionalities?

SQL-Injections can be prevented in PHP scripts, especially in login functionalities, by using prepared statements with parameterized queries. This approach ensures that user input is treated as data rather than executable SQL code, thus preventing malicious SQL injection attacks.

// Using prepared statements to prevent SQL injection in login functionality

// Establishing a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Checking connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Using prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);

// Set parameters and execute
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();

// Check if user exists and login is successful
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    // User authenticated, proceed with login
} else {
    // Invalid credentials, display error message
}

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