What are the best practices for handling form data and database queries in PHP projects?

When handling form data in PHP projects, it is important to sanitize and validate user input to prevent security vulnerabilities such as SQL injection attacks. Additionally, it is crucial to use prepared statements when interacting with a database to prevent SQL injection. Proper error handling should also be implemented to handle any issues that may arise during database queries.

// Sanitize and validate form data
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare and execute a query using a prepared statement
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();

// Proper error handling for database queries
if ($stmt->rowCount() > 0) {
    echo "User added successfully";
} else {
    echo "Error adding user";
}