What is the purpose of using Mysqli Prepared Statements in PHP?

Using Mysqli Prepared Statements in PHP helps prevent SQL injection attacks by separating SQL logic from user input. Prepared statements also improve performance by allowing the database to optimize the query execution plan. Additionally, prepared statements make it easier to reuse queries with different parameters.

// Example of using Mysqli Prepared Statements in PHP
$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();
while ($row = $result->fetch_assoc()) {
    // Process results
}

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