Are there alternative methods to mysql_real_escape_string for sanitizing user input in PHP to prevent SQL injection while avoiding unwanted escape characters in the stored data?
When using mysql_real_escape_string to sanitize user input in PHP, unwanted escape characters may be added to the stored data, which can cause issues. One alternative method to prevent SQL injection while avoiding unwanted escape characters is to use prepared statements with parameterized queries. This method separates the SQL query from the user input, preventing injection attacks without the need for manual escaping.
// Create a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
// Bind parameters
$stmt->bind_param("ss", $username, $password);
// Set parameters and execute the statement
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();
// Close the statement and database connection
$stmt->close();
$mysqli->close();
Related Questions
- How can you format a number to always display with two digits in PHP?
- What potential security risks are associated with not properly handling context switches in PHP, especially when dealing with user input?
- How can PHP users ensure that their code is properly indexed or cached by search engines like Google?