What are the potential security risks associated with directly submitting user input to a database in PHP?
Directly submitting user input to a database in PHP can lead to SQL injection attacks, where malicious SQL code is injected into the input fields to manipulate the database. To prevent this, you should always use prepared statements with parameterized queries to sanitize and validate user input before executing SQL queries.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('INSERT INTO users (username, email) VALUES (:username, :email)');
// Bind parameters and execute the statement
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->execute();