How can one properly handle quotation marks within a SQL query string in PHP?
When including quotation marks within a SQL query string in PHP, it is important to properly escape them to avoid syntax errors or SQL injection vulnerabilities. One common way to handle this is by using the `mysqli_real_escape_string` function to escape any special characters, including quotation marks, before including them in the query string.
// Example code snippet to properly handle quotation marks within a SQL query in PHP
$mysqli = new mysqli("localhost", "username", "password", "database");
// Input data with quotation marks
$input_data = "John's Book";
// Escape special characters, including quotation marks
$escaped_input = $mysqli->real_escape_string($input_data);
// Construct the SQL query with the escaped input
$query = "INSERT INTO books (title) VALUES ('$escaped_input')";
// Execute the query
$result = $mysqli->query($query);
// Check for errors
if (!$result) {
echo "Error: " . $mysqli->error;
}
// Close the connection
$mysqli->close();