How can PHP be used to format text for database entries?

When inserting text into a database using PHP, it is important to properly format the text to ensure it is stored correctly and securely. One common method is to use the mysqli_real_escape_string function to escape special characters in the text before inserting it into the database. This helps prevent SQL injection attacks and ensures the text is stored as intended.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Escape special characters in the text
$text = mysqli_real_escape_string($mysqli, $text);

// Insert the formatted text into the database
$sql = "INSERT INTO table_name (column_name) VALUES ('$text')";
if ($mysqli->query($sql) === TRUE) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;
}

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