How can PHP be used to query a database and display specific results based on certain criteria?
To query a database and display specific results based on certain criteria using PHP, you can use SQL SELECT statements with conditions to filter the data. You can then fetch the results from the database and display them on a webpage using PHP.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query the database based on certain criteria
$sql = "SELECT * FROM table_name WHERE column_name = 'criteria'";
$result = $conn->query($sql);
// Display the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What are the potential drawbacks of manually creating JSON strings in PHP?
- What are the advantages and disadvantages of using Composer's PSR-4 autoloading compared to custom autoloading methods in PHP projects?
- What potential pitfalls should be considered when dealing with arrays of unknown dimensions and elements in PHP?