$dsn = 'mysql:host=localhost;dbname=mydatabase'; $user = 'myusername'; $pass = 'mypassword'; try { $db = new PDO($dsn, $user, $pass); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
$query = 'SELECT * FROM users'; $stmt = $db->query($query); while ($row = $stmt->fetch()) { echo $row['id'] . ': ' . $row['name'] . 'In this example, we execute a SELECT query and get a statement object back. We then loop through the statement object using fetch() to retrieve each row of data and display it to the user. Overall, the PDO library provides a robust and secure way to interact with a database using PHP's object-oriented features.
'; }