How can PHP developers ensure their code is secure from SQL injection when interacting with a MySQL database?
To ensure that PHP code is secure from SQL injection when interacting with a MySQL database, developers should use prepared statements with parameterized queries. This approach separates SQL logic from user input, preventing malicious SQL injection attacks.
// Establish a connection to the MySQL 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 values and execute the query
$username = $_POST['username'];
$stmt->execute();
// Process the query results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the fetched data
}
// Close the statement and the database connection
$stmt->close();
$mysqli->close();