What are the potential security risks of not properly escaping values in SQL code using mysqli_real_escape_string()?
When not properly escaping values in SQL code using mysqli_real_escape_string(), there is a risk of SQL injection attacks where malicious SQL queries can be injected into the code. This can lead to unauthorized access to the database, data manipulation, and potentially data loss. To prevent this, it is important to always escape values before using them in SQL queries.
// Example of properly escaping values in SQL code using mysqli_real_escape_string()
// Establish a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Escape user input for security
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// SQL query with escaped values
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
// Execute the query
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
// Close connection
$mysqli->close();