PDO: Setting Connection Attributes



PHP Data Objects (PDO) Step By Step Tutorial - Part 13: There is a feature in PDO that we called connection attributes. This advance functionality can we use to modify column names, case conversion, and so on. Still confuse? It is simple, look at following sample.
<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// query
$conn->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER);
$sql = "SELECT * FROM books";
$q = $conn->prepare($sql);
$q->execute();

$r = $q->fetch(PDO::FETCH_ASSOC);

print_r($r);

//result:
//Array ( [ID] => 1 
//        [TITLE] => PHP AJAX 
//        [AUTHOR] => Andreas 
//        [DESCRIPTION] => This is good book for learning AJAX 
//        [ON_SALE] => 1 
//        [COVER] => )
?>

Ok, now look at line 13:

$conn->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER);

We use connection attributes, PDO::ATTR_CASE. This attribute controls the case of column names that are returned by the PDOStatement::fetch(). It will work if fetch mode is PDO::FETCH_ASSOC or PDO::FETCH_BOTH, because the row returned as an array the contains columns indexed by their name. From code above, will get result:

Array ( [ID] => 1 
        [TITLE] => PHP AJAX 
        [AUTHOR] => Andreas 
        [DESCRIPTION] => This is good book for learning AJAX 
        [ON_SALE] => 1 
        [COVER] => )

Others value for this attribute: PDO::CASE_LOWER and PDO::CASE_NATURAL.

Previous: PDO: Alternative Retrieve BLOB Data
Next: PDO: Error Mode Attributes



Series this article:
PDO: Introduction PHP Data Object
PDO: Activation PHP Data Objects Extension
PDO: Connecting Use PHP Data Object
PDO: Portable Connection to Database
PDO: Posibble Fetch Mode
PDO: Error Handling
PDO: Prepared Statement
PDO: Positional and Named Placeholders
PDO: Insert and Update Statement Use Prepared Statement
PDO: Prepared Statement and Bound Values
PDO: Working With BLOBs
PDO: Alternative Retrieve BLOB Data
PDO: Setting Connection Attributes
PDO: Error Mode Attributes
PDO: Improve Performance with Persistent Connection
PDO: Getting Connection Attributes


Tag: PHP Data Objects, PDO, dll, extension, PHP extension, attribute Category: PHP Basic Post : April 20th 2008 Read: 3,783 Bookmark and Share

blog comments powered by Disqus