What are some best practices for handling user input in PHP when inserting data into a database?
When handling user input in PHP for insertion into a database, it is important to sanitize the input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries. This helps to separate the SQL query from the user input, ensuring that malicious code cannot be executed.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$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("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
// Sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Execute the prepared statement
$stmt->execute();
// Close the statement and connection
$stmt->close();
$conn->close();