How can SQL injection vulnerabilities be prevented in PHP code?
SQL injection vulnerabilities can be prevented in PHP code by using prepared statements and parameterized queries. This involves separating the SQL query from the user input, allowing the database to distinguish between code and data. By using prepared statements, input is treated as data rather than executable code, effectively preventing SQL injection attacks.
// Using 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 query with a placeholder for user input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set the user input
$username = $_POST['username'];
// Execute the query
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the fetched data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();
Related Questions
- What potential pitfalls should be considered when using PHP for counting and categorizing activities in a form?
- How can additional values be added to an array in PHP while fetching data from a database?
- What is the role of PHP in determining the number of text lines based on width, font, and content in a text field or DIV?