php pdo documentation code example

Example 1: php pdo

const DB_HOST = 'localhost';
const DB_NAME = 'DB_Name';			//Name of the database
const DB_USERNAME = 'username';		//Username to use
const DB_PASSWORD = 'Password';		//Password for that user


// Data Source Name
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;

$options = [
    PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, //make the default fetch be an anonymous object with column names as properties
];

//Create PDO instance
try {
    $pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD, $options);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

Example 2: php query pdo

<?php
$sql =  'SELECT name, color, calories FROM fruit ORDER BY name';
foreach  ($conn->query($sql) as $row) {
    print $row['name'] . "\t";
    print  $row['color'] . "\t";
    print $row['calories'] . "\n";
}
?>

Tags:

Php Example