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.
// 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();
Related Questions
- How can arrays and loops be utilized to improve the organization of PHP code?
- How can we efficiently handle and process multiple checkboxes within a while loop in PHP?
- What are some best practices for handling timestamps and date comparisons in PHP when selecting and moving records between tables based on time criteria?