What are best practices for using PHP functions in database operations?

When using PHP functions in database operations, it is important to sanitize user input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries. This helps to separate SQL logic from user input, making the code more secure.

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the parameter value to the query
$stmt->bindParam(':username', $_POST['username']);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();