What best practices should be followed when handling database connections and queries in PHP to avoid common mistakes like using mysql_affected_rows() incorrectly?

When handling database connections and queries in PHP, it is important to avoid using deprecated functions like mysql_affected_rows() and instead use the appropriate methods provided by the mysqli or PDO extensions. To correctly retrieve the number of affected rows after executing a query, you should use the mysqli_affected_rows() function in the mysqli extension or the rowCount() method in the PDO extension.

// Create a database connection using mysqli
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Execute a query
$query = "UPDATE table SET column = 'value' WHERE id = 1";
$mysqli->query($query);

// Get the number of affected rows
$affected_rows = $mysqli->affected_rows;

// Close the connection
$mysqli->close();

// Output the number of affected rows
echo "Number of affected rows: " . $affected_rows;