Skip to content
PHP Logo

How can PHP be used to filter database queries for only active data records?

To filter database queries for only active data records, you can add a condition to your SQL query that checks for a specific column indicating the record's active status. This column could be a boolean field like 'is_active' where 1 represents active records and 0 represents inactive records. By adding this condition to your query, you can ensure that only active data records are retrieved.

php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Select only active records from the database
$sql = "SELECT * FROM table_name WHERE is_active = 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();