What are the best practices for handling user input and preventing SQL injection in PHP scripts?
- user input validation
- SQL injection prevention
- prepared statements
- mysqli_real_escape_string
- filter_input
SQL injection is a common security vulnerability in PHP scripts where malicious users can input SQL commands into form fields to manipulate the database. To prevent SQL injection, it is important to sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separate SQL code from user input.
// Example of preventing SQL injection using prepared statements
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Sanitize and validate user input
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
// Prepare a SQL statement using prepared statements
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
// Execute the statement
$stmt->execute();
// Fetch the result
$result = $stmt->get_result();
// Use the result as needed
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();
Related questions
-
PHP AJAX jQuery
-
PHP shoutbox archive
-
PHP dynamic updating card storage system