What is the best practice for sanitizing user input before inserting into a MySQL database in PHP?
When inserting user input into a MySQL database in PHP, it is important to sanitize the input to prevent SQL injection attacks. One common method to sanitize user input is to use prepared statements with parameterized queries. This method helps to separate the SQL query from the user input, ensuring that the input is treated as data rather than executable code.
// Assuming $conn is your MySQL database connection
// Sanitize user input using prepared statements
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $input1, $input2);
// Set parameters and execute
$input1 = filter_var($_POST['input1'], FILTER_SANITIZE_STRING);
$input2 = filter_var($_POST['input2'], FILTER_SANITIZE_STRING);
$stmt->execute();
$stmt->close();