What security risks are associated with using mysql_query for database operations in PHP, and how can they be mitigated?
Using mysql_query for database operations in PHP can lead to SQL injection vulnerabilities if user input is not properly sanitized. To mitigate this risk, it is recommended to use prepared statements with parameterized queries instead. This helps prevent malicious SQL injection attacks by separating SQL code from user input.
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set the parameter and execute the query
$username = $_POST['username'];
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the results
}
// Close the statement and connection
$stmt->close();
$mysqli->close();