How can PHP beginners effectively display specific data from a MySQL table in their code?
To display specific data from a MySQL table in PHP, beginners can use SQL queries to retrieve the desired data and then use PHP to display it on the webpage. They can use the mysqli or PDO extension in PHP to connect to the MySQL database and execute the SQL query. Once the data is fetched, they can use PHP to loop through the results and display them on the webpage.
<?php
// Connect to MySQL 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);
}
// SQL query to select specific data from table
$sql = "SELECT column1, column2 FROM table WHERE condition";
$result = $conn->query($sql);
// Display 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";
}
$conn->close();
?>