PHP PDO: Setting Connection Attributes
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 $dbhost = "localhost"; $dbname = "pdo"; $dbuser = "root"; $dbpass = ""; // 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.
0 comments:
Post a Comment