Are there any best practices to follow when handling character encoding and string lengths in PHP for database entries?

When handling character encoding and string lengths in PHP for database entries, it is important to ensure that the database and PHP are using the same character encoding to prevent data corruption. It is also crucial to validate and sanitize user input to prevent SQL injection attacks. Additionally, using prepared statements with parameterized queries can help prevent SQL injection and ensure proper handling of string lengths.

// Set the character encoding for PHP and the database connection
mysqli_set_charset($connection, 'utf8');

// Validate and sanitize user input before inserting into the database
$user_input = mysqli_real_escape_string($connection, $_POST['user_input']);

// Use prepared statements to insert data into the database
$stmt = $connection->prepare("INSERT INTO table_name (column_name) VALUES (?)");
$stmt->bind_param("s", $user_input);
$stmt->execute();