$host = 'localhost'; $dbname = 'mydatabase'; $username = 'myusername'; $password = 'mypassword'; try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); echo "Connected to $dbname database successfully!"; } catch(PDOException $e) { echo "Error: " . $e->getMessage(); }
$sql = "SELECT * FROM users"; $result = $pdo->query($sql); if ($result->rowCount() > 0) { while($row = $result->fetch()) { echo "Name: " . $row['name'] . " | Email: " . $row['email'] . "These PHP examples use the PDO package library to connect to a MySQL database and execute a select query that retrieves data from a table 'users'. PDO provides a clean and consistent interface to access different types of databases and makes it easier to write secure and reusable database code.
"; } } else { echo "No records found."; }