What are some common ways to retrieve and display data from a MySQL database using PHP?
To retrieve and display data from a MySQL database using PHP, you can use the mysqli extension or PDO (PHP Data Objects) to establish a connection to the database, execute a query to retrieve the data, and then loop through the results to display them on a webpage.
// Connect to MySQL database
$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
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display data
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 potential pitfalls can arise when using the mysql_* functions in PHP for database queries?
- What are the implications of using shorthand syntax, like [] for array initialization, in older versions of PHP like 5.3?
- What are potential methods for formatting dates in PHP, specifically for IPTC data?