Quick guide to the new Drupal 7 database layer
This post is my effort to guide you through the whole new abstraction layer for accessing the database server, which comes with the Drupal 7 core distribution. In this blog-post I’ll try to explain to you guys (girls) how this new layer works, without diving into all the details, in order to give you a clear view on this new system.
First of all I’ll explain the benefits of this new system to you. Drupal needed a database system that could easily support multiple database servers in a unified way which preserves the syntax power of SQL. The system was also build to enforce the security checks. There are 6 different types of Query’s which can be called in this database system: Insert, Update, Delete, Merge, Static and Dynamic.
Now lets get it started!
Settings.php
We should start by taking a look at the renewed database definition in the settings.php. In most cases you will be using a drupal site with only one database. For this you should use the following structure.
<?php
$databases['default']['default'] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb’,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘localhost’,
);
?>
The first thing you should notice are the values “default” in the $database array. The first one is the CONNECTION KEY, the second one is the TARGET.
The connection key is a unique identifier for a database connection, there must ALWAYS be a ‘default’ connection key available.
The target is used to define master/slave database structures. If the master (default) isn’t available, the system will search for the slave database. It is also possible to flag a query to run on the slave database. To make this a bit clearer I’ll give you a more complicated database structure.
<?php
$databases['default']['default'] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb1′,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘dbserver1′,
);
$databases['default']['slave'][] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb2′,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘dbserver2‘,
);
?>
In this case, the first database is the default database, the second is the slave databases.
It is also possible to define separate database structures.
<?php
$databases['default']['default'] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb1′,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘dbserver1′,
);
$databases['extra']['default'][] = array(
‘driver’ => ‘mysql’,
‘database’ => ‘drupaldb2′,
‘username’ => ‘username’,
‘password’ => ’secret’,
‘host’ => ‘dbserver2‘,
);
?>
Note that no matter how many connections are defined in the settings file, These connections will not be used by Drupal until they are actually opened.
Select Query
So far for the database connections, now lets take a look at the actual use of query’s in this new database layer. For the regular select query’s not much changes. Here is an example of a select query with a short explanation.
$result = db_query(“SELECT nid, title FROM {node} WHERE type = :type”, array(
‘:type’ => ‘page’,
));
The db_query function uses three arguments, first one is the query string, the second one are the values used to fill up the placeholders. The third one will be explained at the next example.
Note that the placeholder (:type) doesn’t use quotes. Another thing you should take in to account is to put your database names between {}. This is needed for the database system to attache a prefix string if this is defined in your settings.
Now for the third argument of the db_query we will take a look at the following code:
<?php
$result = db_query(“SELECT nid, title FROM {node}”, array(), array(
‘target’ => ’slave’,
));
?>
The third argument is an array of configuration directives to detect the way the query should run. In this case the query runs on the slave database. I won’t go into the details here, because (as I said before) in this blog post I will only pick up the basics of the new database system.
The following is just a handy guide about the way you can use the database query’s results. (Not 100% relevant to this post, but this might come in handy for some of you. The others should just scroll through the code, as if it doesn’t exist).
$result = db_query(“SELECT nid, title FROM {node}”);
foreach ($result as $record) {
// Do something with each $record
}
$record = $result->fetch(); // Use the default fetch mode.
$record = $result->fetchObject(); // Fetch as a stdClass object
$record = $result->fetchField($column_index); // Fetch only one field.
$number_of_rows = $result->rowCount(); //Count the results.
Insert Query
Now we’ve arrived to he fun part. The INSERT, DELETE and UPDATE query’s require that you use the query builder object in order to behave consistently across all different databases. This is where the new object-oriented query API comes in.
The compact INSERT form is the following:
<?php
$nid = db_insert(‘node’)
->fields(array(
‘title’ => ‘Example’,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
))
->execute();
?>
This will result in the following query:
INSERT INTO {node} (title, uid, created) VALUES (’Example’, 1, 1221717405);
Note: If you don’t call the execute() method, the query will not run!
The insert query object can also be used with multiple values. To insert multiple rows you shouldn’t only use fields() but also values(). In this case fields() only defines the fields, but doesn’t put any content into the selected fields. The values() may be called multiple times in order to add more than one line to your database.
<?php
$query = db_insert(’node’)
->fields(array(‘title’, ‘uid’, ‘created’))
->values(array(
array(
‘title’ => ‘Example’,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
),
array(
‘title’ => ‘Example 2′,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
)))
->execute();
?>
Using a ‘foreach’ the code will look like this:
<?php
$values = array(
array(
‘title’ => ‘Example’,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
),
array(
‘title’ => ‘Example 2′,
‘uid’ => 1,
‘created’ => REQUEST_TIME,
),
);
$query = db_insert(‘node’)->fields(array(‘title’, ‘uid’, ‘created’));
foreach ($values as $record) {
$query->values($record);
}
$query->execute();
?>
Update Query
Next stop is the UPDATE query. The update query is pretty straight forward, if you understand how the insert query’s work, it shouldn’t be a problem to understand the update query. Here it goes:
<?php
$num_updated = db_update(‘node’)
->fields(array(
‘uid’ => 5,
’status’ => 1,
))
->condition(‘created’, REQUEST_TIME - 3600, ‘>=’)
->execute();
?>
This will result in the following query:
UPDATE {node} SET uid=5, status=1 WHERE created >= 1221717405;
Not much to explain here, so let’s go to the DELETE query’s.
Delete Query
Again the same story here. The DELETE query is probabily the easiest form of the query object:
<?php
$num_deleted = db_delete(‘node’)
->condition(‘nid’, 5)
->execute();
?>
This will result in the following query:
DELETE FROM {node} WHERE nid=5;
Merge Query
Finally we’ve got to the last one. The MERGE query. This one is a bit more complicated. If you would strip this one down to it’s original form, you will finde that a merge query is actually just the combination of an insert and an update query. In php it would be something like this:
<?php
if (db_query(”SELECT COUNT(*) FROM {example} WHERE id=:id”, array(’:id’ => $id)->fetchField()) {
// Run an update using WHERE id = $id
}
else {
// Run an insert, inserting $id for id
}
?>
In the new database API structure the merge query’s are build up like this:
<?php
db_merge(‘example’)
->key(array(‘name’ => $name))
->fields(array(
‘field1′ => $value1,
‘field2′ => $value2,
))
->execute();
?>
Here the “example” table is used. The specified key field ‘name’ has the value of $name. Now two things could happen.
First option: If the $name value exists in the database, then fields “field1” and “field2” will get an update with the correspondingvalues.
Second option: If the $name value doesn’t exist in the database, a new row will be created in which “name” gets the value $name, “field1” gets the value $field1 and “field2” gets the value $field2.
In some cases the values you want to set will have to be different, according to the fact that the key field does or doesn’t already exist. This can be handled in two ways.
<?php
db_merge(‘example’)
->key(array(‘name’ => $name))
->fields(array(
‘field1′ => $value1,
‘field2′ => $value2,
))
->update(array(
‘field1′ => $alternate1,
))
->execute();
?>
In this case, if the “name” already exists the value of “field1” will be $alternate1, and the value of “field2” will be $value2. If the “name” doesn’t allready exist, $value1 and $value2 will be used.
It is also possible to use expressions. I’ll give you an example in which, if the ‘name’ already exists, the “value1” field will become the current value +1:
<?php
db_merge(‘example’)
->key(array(‘name’ => $name))
->fields(array(
‘field1′ => $value1,
‘field2′ => $value2,
))
->expression(‘field1′, ‘field1 + :inc’, array(‘:inc’ => 1))
->execute();
?>
Note that expression() can be used multiple times, 1 time for each field.
Field updates can also be limited, if the row already exists. In this case, if the “name” already exists, only “field2” will be updated, and “field1” will be ignored:
<?php
db_merge(‘example’)
->key(array(‘name’ => $name))
->fields(array(
‘field1′ => $value1,
‘field2′ => $value2,
))
->updateExcept(‘field1′)
->execute();
?>
This is the end of my quick guide into the new Drupal 7 database layer. Hope you’ve enjoyed it. For more detailed information about this system, I would like to refere to the official drupal database API: http://drupal.org/developing/api/database
Jeroen



Comments
Nice Post
Thu, 01/20/2011 - 06:56.
I came across your page and found the blog really engaging. It not only got me reading but was also very informative. I am hoping to get more such worthwhile content to read. I will subscribe to your site right away. Please keep posting more.
garten
I don’t have time to read
Tue, 12/27/2011 - 00:58.
I don’t have time to read through it all at the minute but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the great job. hotel caldonazzo
David Stanley
Boulevart Labs
Mon, 01/02/2012 - 22:04.
Good idea about using the Rss feeds to keep upto date as this is a great site with some very useful resources
http://www.plumbersinswindon.com
glen james
joomla vs drupal
Fri, 01/06/2012 - 22:38.
Any thoughts on joomla vs drupal in this regard? My programmer is pushing for joomla at the moment...not really sure which way to go... colored contacts
Joe
I've always preferred Joomla
Sat, 01/07/2012 - 22:59.
I've always preferred Joomla and use it on all of my grout stain websites as I have confidence in it.. but they seem to battle back and forth with features.. so anyway, I just stick with what I know since my grout stain sites are my meat and potatoes.
Peter
I will never know about this
Thu, 01/12/2012 - 03:52.
I will never know about this new version if my friend didn’t tell me. It will be very easy to me to edit my queries in the office. However I want to propose some ideas to you to make twitter account or something like that stuff that can keep use update about your news. telephone systems
KatonJaroe
Howdy would you mind letting
Fri, 01/13/2012 - 02:48.
Howdy would you mind letting me know which web host you're using? I've loaded your blog in 3 completely different web browsers and I must say this blog loads a lot quicker then most. Can you suggest a good web hosting provider at a reasonable price? Thanks a lot, I appreciate it! plumbing service london
Howard
Dealing with new one is
Sat, 01/14/2012 - 06:45.
Dealing with new one is always frustrating to me, lol. End users don't see this, but for those who have apps or plugin connected to it, it means some nights without sleep. family adventure holidays
TrajetBela
Great article to read.
Sun, 01/22/2012 - 20:18.
This was really a great and interesting article for me to read. I really do appreciate this. Designer jewellery
Jamie Mills
This was a very cool and fun
Mon, 01/23/2012 - 20:00.
This was a very cool and fun article to read. I really do think that this was so awesome and fun to read. apuestas baloncesto
Anonymous
Very interesting article
Tue, 01/24/2012 - 04:40.
This was really a great and fun article to read. I have enjoyed this great and fun information. This was really a great resource. This was great. Auto insurance for teenagers
Joyce Henderson
devt
Wed, 01/25/2012 - 03:51.
Our cash advance and payday loans are processed instantly. Approval is instant plus your fast cash is safely brought to your money within 1-24hrs. We understand many reasons exist why consumers may very well be looking for a Direct Lender Cash Advances. And, many consumers do not possess admission to revenue sources to pay extra for such items as home or car repairs, bills, or even a wedding anniversary gift.
nuyil
vety
Wed, 01/25/2012 - 07:27.
If you would like accelerate your weight loss, eating healthily, counting calorie consumption and getting some exercise is always recommended. When you Buy Proactol you will get inside information, weight reduction and use videos, personal weight-loss coaching, a $100 weight-loss cash back voucher along with an added bonus of Aci Berry.
barty
Took me time to read all the
Tue, 02/07/2012 - 13:33.
Took me time to read all the comments but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenter here! It's always nice when you can not only be informed but also entertained!
Karmaloop promo codes
Anonymous
tage
Wed, 02/08/2012 - 17:13.
Tra gli adulti tra i 18 e i 64 anni, sono le donne quelle che hanno cercato di più informazioni mediche su Internet (58% contro 43%) e usato chat online per informarsi su tematiche relative alla salute (4% contro 2,5%)”.L’indagine ha rivelato che il 6% degli adulti ha chiesto il rinnovo di una prescrizione via Web, e quasi il 3% ha fissato un appuntamento con un sanitario usando la rete nei 12 mesi precedenti al sondaggio.— Sul sito www.reuters.it le altre notizie Reuters in italiano. Le top news anche su www.twitter.com/reuters_italia
hat
Thanks, I've been hunting for
Fri, 02/10/2012 - 21:41.
Thanks, I've been hunting for facts about this subject matter for ages and yours is the best I have found so far. fire sprinkler
Anonymous
I'm curious to find out what
Fri, 02/10/2012 - 21:52.
I'm curious to find out what blog platform you happen to be working with? I'm having some small security problems with my latest website and I'd like to find something more secure. Do you have any suggestions? leaflet printing
Anonymous
I like what you guys are
Fri, 02/10/2012 - 22:22.
I like what you guys are usually up to. This type of clever work and exposure! Keep up the awesome works guys I've added you guys to my blogroll. Bridging Loans
Anonymous
nice one
Sat, 02/11/2012 - 12:30.
I have been reading your posts regularly. I need to say that you are doing a fantastic job. Please keep up the great work. used nissan altima
kumar
I like what you guys are
Mon, 02/13/2012 - 08:08.
I like what you guys are usually up to. This type of clever work and exposure! Keep up the awesome works guys I've added you guys to my blogroll. chicago limo
Anonymous
I must say you have done a
Mon, 02/13/2012 - 22:34.
I must say you have done a awesome job with this. In addition, the blog loads very quick for me on Opera. Exceptional Blog! home additions
Anonymous
Nice Blog!
Tue, 02/14/2012 - 12:55.
Thanks, I've been searching for facts about this subject matter for years and yours is the best I have found so far.Bank Jobs
jackson321
I'm quite happy to use drupal
Mon, 02/20/2012 - 15:30.
I'm quite happy to use drupal 7, using drupal seems my internet connection became more stable. Compared to previous versions of Drupal, Drupal 7 is much better. Brisbane generators
MugenDesy
Cheap Calls
Tue, 02/21/2012 - 06:59.
Make instant Cheap Calls to all your family members for getting connected requirement of a cheap mode of communication has arrived. And service providers are endeavoring hard.
chanelsourn
barata
Thu, 02/16/2012 - 03:54.
For all those trying to find ELIMINATION CHAMBER 2012 LIVE STREAM videos to observe with their PC on laptops, the two approaches to get it done. You can go for PCTV cards or tv software. Both solutions enable your computer to stream live satellite channels over internet.
teread
Any recommendations for
Fri, 02/17/2012 - 21:53.
Any recommendations for inexperienced blog writers? I'd really appreciate it. Natural Nail Polish
Anonymous
copper sinks
Tue, 02/21/2012 - 10:26.
This is one of the good articles. copper sinks
kumar
map of usa
Tue, 02/21/2012 - 14:17.
ou really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. map of usa
sunder
Looks like this software has
Wed, 02/22/2012 - 12:16.
Looks like this software has been enhanced as well. I will try to download it and use it to support my previous version of software. play bingo
BonarBine
NICE
Wed, 02/22/2012 - 12:16.
Interesting post and thanks for sharing. Sarkari Naukri
sonu12
Great Work
Wed, 02/22/2012 - 13:56.
Thanks for taking the time to talk about this, I really feel strongly about it and adore learning far more on this topic. If feasible, as you acquire expertise, would you thoughts updating your blog with a lot more info? It can be really helpful for me.
boat trader
john
They will take all of users
Wed, 02/15/2012 - 11:07.
They will take all of users to upgrade it to the newest version. So they will give any announcements from the software too.
ampliacion de hipotecas
ampliacion de h...
I do not think Drupal 7 has
Sun, 02/19/2012 - 09:44.
I do not think Drupal 7 has been updated on this page. Yet I look for in a few days but I did not get anywhere. cheapest student car insurance
JerukOren
good one
Sat, 02/18/2012 - 09:04.
Therefore useful website! Big thanks a lot! Many thanks the best time viewing your internet site. It is a new pleasure comprehending a web site like this filled up with good information. Appreciate it!
car accident attorney
smith
Drupal 7 I used to support
Tue, 02/21/2012 - 06:25.
Drupal 7 I used to support the performance of my website. Although I do not understand how to operate it, but I am satisfied with the results. Lake Ridge VA private school
MeganDois
good one
Tue, 02/21/2012 - 10:30.
You have posted very informative thing. I am excitedly waiting for you next post.Thanks and keep it up!Zuschüsse
Cressida
They bring their users to the
Mon, 02/13/2012 - 23:51.
They bring their users to the newest version. So they will feels the difference of the new one and old one.
Backgammon rules
Backgammon rules
I found this post to be very
Tue, 02/14/2012 - 01:08.
I found this post to be very educational. Thank you for broadening my knowledge of this subject. No doubt its a great piece of writing as well. Thanks McCormick Robert
Anonymous
nice one
Tue, 02/14/2012 - 12:22.
It seems too Shopping Saver Australia complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it! Legendario Elixir
kumar
nice one
Fri, 02/17/2012 - 10:52.
i am not a good reader but this written in simple and helpful.Encino dentist
kumar
There are 6 different types
Sat, 02/18/2012 - 11:17.
There are 6 different types of Query’s which can be called in this database system: Insert, Update, Delete, Merge, Static and Dynamic. Penny Stocks
Anonymous
nice one
Mon, 02/20/2012 - 07:55.
I have read which are really not tht good. I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well..
Existenzgründung aus der Arbeitslosigkeit mit Gründungszuschuss und Einstiegsgeld
alina
Criminals want the biggest
Tue, 02/21/2012 - 08:54.
Criminals want the biggest bang for their malware buck which means the dominant operating systems, browsers, platforms etc. are always going to be the better targets
Netsuite Support || Netsuite Scripting
Anonymous
nice one..
Tue, 02/21/2012 - 10:35.
Great job here. I really enjoyed what you had to say. Keep going because you definitely bring a new voice to this subject. Escorts
shanwarn
nice one
Mon, 02/20/2012 - 08:10.
I am impressed by the way you covered this topic. It is not often I come across a blog with captivating articles like yours. I will note your feed to keep up to date with your approaching updates. Just striking and do uphold up the good work.
Beraternetzwerk
angela
I have been interested in
Mon, 02/20/2012 - 16:18.
I have been interested in this topic for quite some time. Thanks a lot for going into it.. dental hygiene schools in texas
Anonymous
Thanks for the well
Mon, 02/20/2012 - 16:20.
Thanks for the well-researched post. I'll definitely come back soon.. London Escorts
Anonymous
I agree with you. This post
Tue, 02/21/2012 - 17:25.
I agree with you. This post is truly inspirational.. Keep up the good work! we buy houses arizona
Anonymous
Thanks for bringing all the
Tue, 02/21/2012 - 17:26.
Thanks for bringing all the tips into 1 post. It has saved me lots of time! we buy houses arizona
Anonymous
I recently came across your
Tue, 02/21/2012 - 17:26.
I recently came across your blog and have been reading along. I'll be looking forward to your next blog post! we buy houses arizona
Anonymous
Pages
Add new comment