How can a beginner effectively output SQL data in a PHP file?
To output SQL data in a PHP file as a beginner, you can use the mysqli extension to establish a connection to your database and execute a query to retrieve the data. You can then loop through the results and display them on your webpage using PHP echo statements.
<?php
// Establish a connection to your 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);
}
// Execute a query to retrieve data
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Loop through the results and display them
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>