What are the best practices for executing multiple SQL queries based on user input in PHP?
When executing multiple SQL queries based on user input in PHP, it is important to sanitize and validate the user input to prevent SQL injection attacks. One approach is to use prepared statements with parameterized queries to safely execute the SQL queries. Additionally, it is recommended to handle errors gracefully by implementing error handling mechanisms to catch and log any potential issues that may arise during the execution of the queries.
<?php
// Assuming $userInput is the user input containing SQL queries
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Sanitize and validate user input
$queries = explode(';', $userInput);
foreach($queries as $query) {
$stmt = $pdo->prepare($query);
$stmt->execute();
}
// Handle errors gracefully
if($stmt->errorCode() !== '00000') {
$errorInfo = $stmt->errorInfo();
error_log('SQL Error: ' . $errorInfo[2]);
}
?>