What are common methods for displaying data from a MySQL database in a PHP page?
One common method for displaying data from a MySQL database in a PHP page is to use the mysqli extension in PHP to connect to the database, execute a query to retrieve the data, and then loop through the results to display them on the page. Another method is to use PDO (PHP Data Objects) to interact with the database and fetch the data. Both methods involve establishing a connection to the database, querying for the desired data, and then displaying it in a structured format on the PHP page.
<?php
// Establish a connection to the MySQL database using mysqli
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve data from a table
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display the data in a table format
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['column1'] . "</td><td>" . $row['column2'] . "</td></tr>";
}
echo "</table>";
// Close the connection
$conn->close();
?>
Keywords
Related Questions
- In what scenarios is it necessary to use IFrames in PHP, and what are some alternative approaches to consider when dealing with cross-server PHP files without direct access to FTP or databases?
- How can PHP syntax be correctly written to output dynamic content within a specific category in Wordpress?
- What are some potential pitfalls when using PHP sessions to identify users and store data?