What are some common pitfalls when using mysqli to connect to a MySQL server in PHP?

One common pitfall when using mysqli to connect to a MySQL server in PHP is not handling connection errors properly. It is important to check for connection errors and handle them gracefully to prevent unexpected behavior in your application. Another pitfall is not setting the correct character set for the connection, which can lead to encoding issues. Additionally, not properly sanitizing user input before executing queries can leave your application vulnerable to SQL injection attacks.

// Correctly handling connection errors
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Setting the correct character set
$mysqli->set_charset("utf8");

// Sanitizing user input before executing queries
$user_input = $mysqli->real_escape_string($_POST['user_input']);
$query = "SELECT * FROM table WHERE column = '$user_input'";
$result = $mysqli->query($query);