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
- How can one ensure proper HTML sanitization and formatting when processing form data in PHP?
- What best practices should be followed when handling values passed through the POST method in PHP to ensure successful data transfer between pages?
- What are the best practices for exporting and importing databases in PHP to avoid data loss or corruption?