How can SQL injection vulnerabilities be mitigated when using mysqli_query in PHP?
SQL injection vulnerabilities can be mitigated when using mysqli_query in PHP by using prepared statements with parameterized queries. This approach ensures that user input is treated as data rather than executable code, preventing malicious SQL injection attacks.
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a parameterized query using placeholders
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind parameters and execute the query
$stmt->bind_param("s", $username);
$username = $_POST['username'];
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();
Related Questions
- How can database structure impact the functionality of PHP scripts, and what considerations should be made when designing database tables for PHP applications?
- What are the limitations of using PHP to handle user interaction before form submission?
- What are the potential pitfalls of using strpos() function in PHP to check for the presence of a word in a string?