What best practices should be followed when inserting user-submitted data into a MySQL database in PHP?
When inserting user-submitted data into a MySQL database in PHP, it is important to use prepared statements to prevent SQL injection attacks. This involves using parameterized queries to separate the SQL code from the user input data, ensuring that the data is properly sanitized before being inserted into the database.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Prepare a SQL statement with placeholders for user input
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");
// Bind the user input data to the placeholders
$stmt->bindParam(':value1', $userInput1);
$stmt->bindParam(':value2', $userInput2);
// Execute the statement
$stmt->execute();