What best practices should be followed when handling encoding in PHP for database interactions?

When handling encoding in PHP for database interactions, it is important to ensure that data is properly sanitized and encoded to prevent SQL injection attacks. One best practice is to use prepared statements with parameterized queries to safely pass data to the database without the risk of malicious input. Additionally, setting the correct character encoding for the database connection can help prevent issues with special characters.

// 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);
}

// Set the character encoding for the connection
$conn->set_charset("utf8");

// Prepare a parameterized query to insert data into the database
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

// Sanitize and encode user input before binding parameters
$value1 = htmlspecialchars($_POST['input1']);
$value2 = htmlspecialchars($_POST['input2']);

// Execute the query
$stmt->execute();

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