How can SQL statements be used effectively to retrieve specific data for display in PHP?
To retrieve specific data for display in PHP using SQL statements, you can use the SELECT query along with conditions to filter the data you need. You can then fetch the results from the database and display them in your PHP script.
<?php
// Establish a connection to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to retrieve specific data
$sql = "SELECT * FROM table_name WHERE condition = 'value'";
// Execute the query
$result = $conn->query($sql);
// Display the retrieved data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column 1: " . $row["column1"]. " - Column 2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>