Is it necessary to escape quotes in SQL queries in PHP?
When constructing SQL queries in PHP, it is necessary to escape quotes to prevent SQL injection attacks and ensure the query executes correctly. This can be done using functions like mysqli_real_escape_string() or prepared statements to safely handle user input containing quotes.
// Example of using mysqli_real_escape_string()
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$user_input = "John's Pizza";
$escaped_input = $mysqli->real_escape_string($user_input);
$sql = "INSERT INTO products (name) VALUES ('$escaped_input')";
$result = $mysqli->query($sql);
if ($result) {
echo "Record inserted successfully";
} else {
echo "Error: " . $mysqli->error;
}
$mysqli->close();
Related Questions
- What are the best practices for handling network-related information in PHP applications?
- What are the best practices for handling database queries in PHP to ensure efficient and accurate results?
- How can mod_rewrite be used to clean up URLs and improve SEO for PHP websites with language switching functionality?