What is the best practice for filtering database query results based on a specific status value in PHP?
When filtering database query results based on a specific status value in PHP, the best practice is to use a prepared statement with a parameterized query to prevent SQL injection attacks. You can use a placeholder in the query for the status value and bind the actual value to the placeholder before executing the query. This approach ensures the security of your application and allows for efficient filtering of results based on the specified status value.
// Assuming $status is the specific status value to filter by
$status = "active";
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a parameterized query to select data based on status
$stmt = $pdo->prepare("SELECT * FROM my_table WHERE status = :status");
// Bind the status value to the placeholder
$stmt->bindParam(':status', $status);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Output or process the filtered results
foreach ($results as $row) {
// Output or process each row
}