What are the best practices for securing PHP scripts against SQL injections when using user input in queries?
To secure PHP scripts against SQL injections when using user input in queries, it is essential to use prepared statements with parameterized queries. This method helps separate SQL logic from user input, preventing malicious SQL code from being executed. Additionally, input validation and sanitization should be performed to ensure that only expected data types and formats are accepted.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare a SQL statement with a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set and execute the query with sanitized user input
$username = mysqli_real_escape_string($conn, $_POST['username']);
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Output the results
}
// Close the statement and connection
$stmt->close();
$conn->close();