In what ways can PHP be optimized for efficiency and security when dealing with database operations for web development projects?

Issue: To optimize PHP for efficiency and security when dealing with database operations in web development projects, it is important to use prepared statements to prevent SQL injection attacks and to minimize unnecessary database queries. Code snippet:

// Establish a connection to the database
$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);
}

// Use prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

// Fetch data from the result set
while ($row = $result->fetch_assoc()) {
    // Process the data
}

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