In PHP, what best practices should be followed when handling user input from a form field and storing it in a database to avoid errors related to special characters like quotes?

When handling user input from a form field and storing it in a database, it's important to sanitize the input to prevent SQL injection attacks and errors related to special characters like quotes. One common approach is to use prepared statements with parameterized queries to safely insert data into the database without the need to escape special characters manually.

// Assuming $conn is the database connection object

// Sanitize user input
$userInput = $_POST['user_input'];
$sanitizedInput = mysqli_real_escape_string($conn, $userInput);

// Prepare and execute the query using a prepared statement
$stmt = $conn->prepare("INSERT INTO table_name (column_name) VALUES (?)");
$stmt->bind_param("s", $sanitizedInput);
$stmt->execute();
$stmt->close();