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 ensure that the current value in a dropdown field is displayed at the top, with other values below it?
- What are some common issues when configuring PHP extensions like php_mysql.dll in the php.ini file?
- What are some best practices for dynamically generating buttons in PHP, especially when the button content is stored in a database?