What best practices should be followed when querying data from a database in PHP to ensure accurate results and avoid errors?

When querying data from a database in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure the accuracy of the results. Additionally, always sanitize user input to avoid errors and validate the data before executing the query.

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

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE column_name = :value");

// Bind the parameter value
$value = $_POST['input_value'];
$stmt->bindParam(':value', $value);

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

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

// Loop through the results
foreach($results as $row){
    // Process the data as needed
}