SlideShare a Scribd company logo
Database API
Your new friend
DrupalCamp Spain 2014
Francisco Alonso Borragán
About me
Francisco Alonso Borragán
Drupal Developer
www.kikoalonsob.com
IRC #drupal_es : kikoalonsob
Twitter : @kikoalonsob
Index
1. Intro
2. Static queries
3. Dynamic queries
1. Select queries
2. Insert queries
3. Update queries
4. Delete queries
4. Query alteration
5. Working against other DB
6. Questions
Intro
Abstraction layer for accessing database servers
Support multiple database servers
Dynamic construction of queries
Enforce security checks and good practices
Provide an interface for intercept and modify queries
Static queries
Static queries
Explicit query string (Better for performance)
Used for simple select queries
Returns a prepared statement object, already executed
db_query($query,array$args=array(),array$options=array());
Static queries
$uid=1;
$result=db_query('SELECTn.nid,n.title,n.created
FROM{node}nWHEREn.uid=:uid',
array(':uid'=>$uid),
array('fetch'=>PDO::FETCH_ASSOC)
);
Prefixing
All table names must be wrapped in { }
Static queries
$uid=1;
$result=db_query('SELECTn.nid,n.title,n.created
FROM{node}nWHEREn.uid=:uid',
array(':uid'=>$uid),
array('fetch'=>PDO::FETCH_ASSOC)
);
Placeholders
Literal or an array that will be inserted into a query for execution
Static queries
$uid=1;
$result=db_query('SELECTn.nid,n.title,n.created
FROM{node}nWHEREn.uid=:uid',
array(':uid'=>$uid),
array('fetch'=>PDO::FETCH_ASSOC)
);
Query options
Set the query behavior (typically only two directives)
target (master,slave)
fetch (PDO::FETCH_OBJ, PDO::FETCH_ASSOC, etc)
Static queries
$uid=1;
$result=db_query('SELECTn.nid,n.title,n.created
FROM{node}nWHEREn.uid=:uid',
array(':uid'=>$uid),
array('fetch'=>PDO::FETCH_ASSOC)
);
and...
how to use the result?
Iterating over the result
with a foreach loop...
foreach($resultas$record){
//Dosomethingwitheach$record
}
Iterating over the result
...or with a while loop
if($result){
while($record=$result->fetch()){
//Dosomethingwitheach$record
}
}
Instead of use $result->fetch(), we can use:
$result->fetchAssoc()//tofetchanassociativearray
$result->fetchObject()//tofetchanobject
$result->fetchField($column_index)//tofetchjustasinglefield
All results at once into an
array
//Indexedarray
$result->fetchAll()
//Associativearraykeyedby$fieldvalue
$result->fetchAllAssoc($field)
//associativearrayoffield1=>field2
$result->fetchAllKeyed()
//associativearrayoffieldI=>fieldj
$result->fetchAllKeyed(i,j)
//Singlearray
$result->fetchCol(i=0)
Dynamic
queries
Dynamic
queries
Dynamically built
Used for some select queries
Used for all insert, update, delete and merge queries
Select queries
Always start using
$query=db_select($table,$alias=NULL,array$options=array());
and need at least one field
$query->fields(‘table_or_alias’,array(‘field_1’,’field_2’));
$query->fields(‘table_or_alias’);//Alltablefields
Joins
You can add one or more joins
$query->join($table,$alias=NULL,$condition=NULL,$arguments=array());
* joincan be replaced by innerJoin, rightJoinor leftJointoo.
Conditional clauses
$query->condition($field,$value=NULL,$operator=NULL);
$operatoraccepts =, <, >=, IN, LIKE, BETWEEN, etc…
By default, conditions are concatenated with AND
Use db_and(), db_or()or db_xor()to overwrite it
db_or=db_or();
$db_or->condition(‘type’,‘page’,‘=’);
$db_or->condition(‘field_1’,array(12,15),‘IN’);
$query->condition($db_or);
Ordering
$query->orderBy($field,$direction='ASC')
Grouping
$query->groupBy($field)
Ranges and limits
$query->range($start=NULL,$length=NULL)
how to use the result?
Remember: db_query()returns a prepared statement object, already
executed
But ... db_select()returns a SelectQuery object
Now, you can use the $resultlike in static queries
$result=$query->execute()
Insert queries
Always start using:
$query=db_insert($table,array$options=array());
We have to specify values with fields($value)function
Compact form: The preferred form for most Insert queries
Degenerate form: Useful for running a multi-insert query
Compact form
A simple $key => $valuearray where $keyis the field name.
$query=->fields(array(
'title'=>'Example',
'uid'=>1,
)
)
$query->execute();
Degenerate form
fields()only specifies field names
values()specifies a $key => $valuearray
$query=db_insert('node');
$query->fields(array('title','uid'));
$values=array(
array('title'=>'Example','uid'=>1),
array('title'=>'Example2','uid'=>1)
);
foreach($valuesas$record){
$query->values($record);
}
$query->execute();
Insert based on the result of a select
Build the select query, but not execute!!
$query=db_insert('node');
->from($select);
$query->execute();
Update queries
Similar to insert queries, start using
$query=db_update($table,array$options=array());
and continuate specifying fields (like in insert queries) and conditions
$query->fields($table_alias,array$fields=array())
->condition($field,$value,$operator);
$query->execute();
Delete queries
Yes... start using
$query=db_delete($table,array$options=array());
and continue with a condition
$query->condition($field,$value,$operator)
->execute();
Query alteration
Most interesting feature of this API (IMHO)
Allow other modules to alter queries on the fly
Preparing your query
Add aone or more tags to identify the query
$query->addTag('myTag');
Attach meta data to provide additional context (Opt.)
$query->addMetaData('node',$node);
How to modify a query?
In your custom module, you can use
hook_query_alter(QueryAlterableInterface$query)
//or
hook_query_TAG_alter(QueryAlterableInterface$query)
and inside them...
$query->hasTag($tag);
$query->hasAnyTag($tag_1,$tag_2);
$query->hasAllTags($tag_1,$tag_2);
$query->getMetaData($key);
In your mymodule.views.inc
hook_views_query_alter(&$view,&$query);
Can I modify a views query?
Yes, you can!
Working against
other DB
In your settings.php:
$databases=array();
$databases['default']['default']=array(
//Drupal'sdefaultcredentialshere.
);
$databases['my_other_db']['default']=array(
//Yoursecondarydatabase'scredentialshere.
);
Working against
other DB
In your module
db_set_active('my_other_db');
db_set_active();//Connecttodefault
Working against
other DB
You can define the connection directly in your module
$my_other_db=array(
'database'=>'my_other_db',
'username'=>'username',
'password'=>'password',
'host'=>'localhost',
'driver'=>'mysql',
);
Database::addConnectionInfo('YourDatabaseKey','default',$my_other_db);
db_set_active('YourDatabaseKey');
2
thanks

More Related Content

What's hot (19)

PPTX
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc
 
KEY
Php 101: PDO
Jeremy Kendall
 
PDF
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
PDF
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
PDF
The Origin of Lithium
Nate Abele
 
PDF
Everything About PowerShell
Gaetano Causio
 
PDF
Future of HTTP in CakePHP
markstory
 
ODP
Patterns for slick database applications
Skills Matter
 
KEY
Unit testing zend framework apps
Michelangelo van Dam
 
PDF
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
PDF
PHP Language Trivia
Nikita Popov
 
PDF
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
Rafael Dohms
 
PPTX
Oops in php
Gourishankar R Pujar
 
PDF
Doctrine fixtures
Bill Chang
 
PDF
The State of Lithium
Nate Abele
 
PPTX
Laravel
Sayed Ahmed
 
PDF
The Zen of Lithium
Nate Abele
 
PDF
You code sucks, let's fix it
Rafael Dohms
 
PDF
Php unit the-mostunknownparts
Bastian Feder
 
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc
 
Php 101: PDO
Jeremy Kendall
 
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
The Origin of Lithium
Nate Abele
 
Everything About PowerShell
Gaetano Causio
 
Future of HTTP in CakePHP
markstory
 
Patterns for slick database applications
Skills Matter
 
Unit testing zend framework apps
Michelangelo van Dam
 
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
PHP Language Trivia
Nikita Popov
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
Rafael Dohms
 
Doctrine fixtures
Bill Chang
 
The State of Lithium
Nate Abele
 
Laravel
Sayed Ahmed
 
The Zen of Lithium
Nate Abele
 
You code sucks, let's fix it
Rafael Dohms
 
Php unit the-mostunknownparts
Bastian Feder
 

Viewers also liked (20)

PDF
Smc capital camp 2014
Phase2
 
PDF
CapitalCamp Features
Phase2
 
PPT
Slick Data Sharding: Slides from DrupalCon London
Phase2
 
PPTX
Zuluk | Zuluk Package | Zuluk Silk Route | Zuluk Tour
Naturewings
 
PDF
OA2 for Goverment
Phase2
 
PPTX
Unit Plan PowerPoint
colbert6
 
PDF
Polizze C.A.R. e E.A.R - Copertura dei danni per tutti gli impianti di produz...
Ergowind srl
 
DOCX
ASSURE method
colbert6
 
DOCX
Arts and bots
colbert6
 
PDF
I meccanismi di incentivazione delle fonti rinnovabili: presente e futuro
Ergowind srl
 
DOCX
Facebook screenshots
colbert6
 
DOCX
Assure method
colbert6
 
DOCX
Assure method assignment
colbert6
 
PPTX
наталія боднар презентація
Natalya Bodnar
 
PPTX
Chocolate toxicity in animals by Dr.Amandeep
Amen Deep
 
PPTX
Unit plan revised
colbert6
 
PPTX
Calf bloat /abomasal tympany by Dr.Amandeep
Amen Deep
 
PDF
LO SVILUPPO DELL’EOLICO DI PICCOLA TAGLIA
Ergowind srl
 
PPTX
Radiographic Artifacts In Animals By Dr.Amandeep GADVASU
Amen Deep
 
PPTX
Rodenticide Toxicity In Animals by Dr.Amandeep
Amen Deep
 
Smc capital camp 2014
Phase2
 
CapitalCamp Features
Phase2
 
Slick Data Sharding: Slides from DrupalCon London
Phase2
 
Zuluk | Zuluk Package | Zuluk Silk Route | Zuluk Tour
Naturewings
 
OA2 for Goverment
Phase2
 
Unit Plan PowerPoint
colbert6
 
Polizze C.A.R. e E.A.R - Copertura dei danni per tutti gli impianti di produz...
Ergowind srl
 
ASSURE method
colbert6
 
Arts and bots
colbert6
 
I meccanismi di incentivazione delle fonti rinnovabili: presente e futuro
Ergowind srl
 
Facebook screenshots
colbert6
 
Assure method
colbert6
 
Assure method assignment
colbert6
 
наталія боднар презентація
Natalya Bodnar
 
Chocolate toxicity in animals by Dr.Amandeep
Amen Deep
 
Unit plan revised
colbert6
 
Calf bloat /abomasal tympany by Dr.Amandeep
Amen Deep
 
LO SVILUPPO DELL’EOLICO DI PICCOLA TAGLIA
Ergowind srl
 
Radiographic Artifacts In Animals By Dr.Amandeep GADVASU
Amen Deep
 
Rodenticide Toxicity In Animals by Dr.Amandeep
Amen Deep
 
Ad

Similar to Database API, your new friend (20)

KEY
Spl Not A Bridge Too Far phpNW09
Michelangelo van Dam
 
PDF
Quebec pdo
Rengga Aditya
 
PPTX
php2.pptx
ElieNGOMSEU
 
PDF
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Vineet Kumar Saini
 
PDF
Php tips-and-tricks4128
PrinceGuru MS
 
KEY
Zf Zend Db by aida
waraiotoko
 
PDF
Using web2py's DAL in other projects or frameworks
Bruno Rocha
 
PPT
Quebec pdo
Valentine Dianov
 
PDF
The History of PHPersistence
Hugo Hamon
 
PDF
Sqlite perl
Ashoka Vanjare
 
PDF
Php summary
Michelle Darling
 
PPTX
CodeIgniter Class Reference
Jamshid Hashimi
 
PDF
Mongo Presentation by Metatagg Solutions
Metatagg Solutions
 
PPT
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
PDF
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
PDF
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
PDF
Dependency Injection
Rifat Nabi
 
PDF
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
Supriya Radhakrishna
 
PDF
RMySQL Tutorial For Beginners
Rsquared Academy
 
Spl Not A Bridge Too Far phpNW09
Michelangelo van Dam
 
Quebec pdo
Rengga Aditya
 
php2.pptx
ElieNGOMSEU
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Vineet Kumar Saini
 
Php tips-and-tricks4128
PrinceGuru MS
 
Zf Zend Db by aida
waraiotoko
 
Using web2py's DAL in other projects or frameworks
Bruno Rocha
 
Quebec pdo
Valentine Dianov
 
The History of PHPersistence
Hugo Hamon
 
Sqlite perl
Ashoka Vanjare
 
Php summary
Michelle Darling
 
CodeIgniter Class Reference
Jamshid Hashimi
 
Mongo Presentation by Metatagg Solutions
Metatagg Solutions
 
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
Dependency Injection
Rifat Nabi
 
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
Supriya Radhakrishna
 
RMySQL Tutorial For Beginners
Rsquared Academy
 
Ad

Recently uploaded (20)

PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
July Patch Tuesday
Ivanti
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 

Database API, your new friend