Certainly! Here’s an example of PHP code that demonstrates how to retrieve and list data from a MySQL database using the PDO extension:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
try {
// Create a new PDO instance
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare the SQL statement
$sql = "SELECT * FROM your_table";
$stmt = $conn->prepare($sql);
// Execute the statement
$stmt->execute();
// Fetch all rows as an associative array
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Process the retrieved data
foreach ($rows as $row) {
echo "Column1: " . $row['column1'] . "<br>";
echo "Column2: " . $row['column2'] . "<br>";
echo "Column3: " . $row['column3'] . "<br>";
echo "-------------------------<br>";
}
} catch(PDOException $e) {
echo "Error retrieving data: " . $e->getMessage();
}
$conn = null;
?>
Make sure to replace the following placeholders with your own values:
localhost
: The hostname or IP address of your MySQL server.your_username
: The username for accessing the MySQL database.your_password
: The password for accessing the MySQL database.your_database
: The name of the MySQL database.your_table
: The name of the table from which you want to retrieve data.column1, column2, column3
: The names of the columns in the table.
This code uses the PDO extension in PHP to establish a connection to the MySQL database, prepare an SQL SELECT statement, execute the statement, fetch all rows as an associative array, and iterate over the rows to process and display the retrieved data. The code also handles any potential exceptions that may occur during the execution.