$hostname = "localhost"; $username = "myusername"; $password = "mypassword"; $dbname = "mydatabase"; try { $conn = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password); echo "Connected successfully!"; } catch (PDOException $e) { die("Connection failed: " . $e->getMessage()); }
$sql = "SELECT * FROM users"; $stmt = $conn->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($result as $row) { echo "Name: " . $row['name'] . " Email: " . $row['email'] . "In this example, we prepare a SQL statement that selects all data from a `users` table. We execute the statement and fetch all the results using `fetchAll()`. We then loop through each row and display the name and email columns.
"; }