What are the potential risks of SQL Injection in PHP and how can they be mitigated?
SQL Injection in PHP occurs when user input is not properly sanitized before being used in SQL queries, allowing malicious users to execute arbitrary SQL commands. To mitigate this risk, developers should use prepared statements with parameterized queries instead of directly concatenating user input into SQL queries.
// Mitigating SQL Injection using prepared statements
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a SQL query using a prepared statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();
// Fetch results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process results
}
// Close statement and connection
$stmt->close();
$mysqli->close();