1
2<?php
3$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
4foreach ($conn->query($sql) as $row) {
5 print $row['name'] . "\t";
6 print $row['color'] . "\t";
7 print $row['calories'] . "\n";
8}
9?>
10
11
1const DB_HOST = 'localhost';
2const DB_NAME = 'DB_Name'; //Name of the database
3const DB_USERNAME = 'username'; //Username to use
4const DB_PASSWORD = 'Password'; //Password for that user
5
6
7// Data Source Name
8$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
9
10$options = [
11 PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
12 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
13 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, //make the default fetch be an anonymous object with column names as properties
14];
15
16//Create PDO instance
17try {
18 $pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD, $options);
19} catch (PDOException $e) {
20 echo 'Connection failed: ' . $e->getMessage();
21}