What best practices should be followed when creating and inserting data into database tables in PHP?

When creating and inserting data into database tables in PHP, it is important to follow best practices to ensure data integrity and security. This includes using prepared statements to prevent SQL injection attacks, validating user input to prevent malicious data entry, and properly sanitizing data before inserting it into the database.

// 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 to the placeholders
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);

// Validate and sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Execute the prepared statement
$stmt->execute();