How can SQL Injections be prevented in PHP when interacting with a database?
SQL Injections can be prevented in PHP by using prepared statements with parameterized queries. This method allows the database engine to distinguish between code and data, thus preventing malicious SQL injection attacks.
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare a SQL statement using a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Execute the statement with user input
$username = $_POST['username'];
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the retrieved data
}
// Close the connection
$stmt->close();
$conn->close();
Related Questions
- What could be potential reasons for the values not being transferred via email in the PHP contact form?
- How can one ensure that the session.save_path setting is correctly configured in PHP to avoid errors?
- How can PHP be used to dynamically highlight the current page in a menu with over 100 subpages?