How can PHP be used to sanitize user input before inserting it into a database to prevent SQL errors?
To prevent SQL errors, user input should be sanitized before inserting it into a database to avoid SQL injection attacks. One way to sanitize user input is by using prepared statements with parameterized queries in PHP. This method separates the SQL query from the user input, making it safer to insert data into the database.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Sanitize user input
$userInput = $_POST['user_input'];
$cleanInput = filter_var($userInput, FILTER_SANITIZE_STRING);
// Prepare a SQL query using a parameterized query
$stmt = $pdo->prepare("INSERT INTO my_table (column_name) VALUES (:input)");
$stmt->bindParam(':input', $cleanInput);
// Execute the query
$stmt->execute();