How can MySQL data be retrieved upon page load in PHP?
To retrieve MySQL data upon page load in PHP, you can use PHP's MySQLi or PDO extension to connect to the database, execute a query to fetch the desired data, and then display it on the webpage. You can achieve this by writing PHP code that connects to the database, fetches the data using a SELECT query, and then displays the data in the desired format 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);
}
// Fetch data from MySQL database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display data on the webpage
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What are some best practices for efficiently handling and processing data stored in a database in PHP?
- What role does the header() function play in PHP and how can it be utilized for page redirection within a script?
- What potential issues can arise when using PHP to interact with a database, as seen in the provided code snippet?