What are the potential security risks associated with using mysql_real_escape_string in PHP for database queries?
Using `mysql_real_escape_string` in PHP for database queries can still leave your application vulnerable to SQL injection attacks if not used correctly. It is recommended to use parameterized queries with prepared statements instead, as they provide a more secure way to interact with the database and prevent SQL injection attacks.
// Using parameterized queries with prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind parameters
$stmt->bind_param("s", $username);
// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();
// Get results
$result = $stmt->get_result();
// Fetch data
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close statement and connection
$stmt->close();
$mysqli->close();