What are the benefits of using Prepared Statements in PHP when querying a database?

Using Prepared Statements in PHP when querying a database helps prevent SQL injection attacks by separating SQL code from user input. It also improves performance by allowing the database to compile the query only once and reuse it with different parameters. Additionally, Prepared Statements make code more readable and maintainable by separating the query logic from the data.

// Example of using Prepared Statements in PHP to query a database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = "john_doe";
$stmt->execute();

// Get results
$result = $stmt->get_result();

// Loop through results
while ($row = $result->fetch_assoc()) {
    // Process each row
}

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