What best practices should be followed when using MySQL queries in PHP scripts to prevent server performance issues?

When using MySQL queries in PHP scripts, it is important to follow best practices to prevent server performance issues. One common issue is not properly sanitizing user input, which can lead to SQL injection attacks and degrade server performance. To prevent this, always use prepared statements with parameterized queries to securely interact with the database.

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

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

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

// Process results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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