What are the steps involved in composing and sending a query to a database using PHP?

When composing and sending a query to a database using PHP, you need to establish a connection to the database, construct the SQL query, execute the query, and handle the results accordingly. This involves using functions like mysqli_connect, mysqli_query, and mysqli_fetch_assoc.

// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database_name");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Construct the SQL query
$sql = "SELECT * FROM table_name";

// Execute the query
$result = mysqli_query($connection, $sql);

// Handle the results
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
mysqli_close($connection);