How can you retrieve specific data from a database using PHP?

To retrieve specific data from a database using PHP, you can use SQL queries with the SELECT statement. You need to establish a connection to the database, execute the query, and fetch the results. Make sure to properly sanitize user input to prevent SQL injection attacks.

<?php
// Establish a connection 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);
}

// Prepare and execute a SQL query to retrieve specific data
$sql = "SELECT column1, column2 FROM table WHERE condition = 'value'";
$result = $conn->query($sql);

// Fetch the results and output them
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
$conn->close();
?>