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();
Related Questions
- What are some common pitfalls to avoid when working with numerical operations in PHP?
- What are the differences between POSIX regular expressions used in ereg functions and PCRE (Perl-compatible regular expressions) in PHP?
- What are the potential pitfalls of using the same variable name for different purposes in PHP functions?