Context
Playing with two of Feeddemon’s SQLite databases, tags.fdb and feeds.fdb, I created this working raw query (tested using Firefox’ handy addon SQLite Manager):
SELECT tbl_tags.tag_name, feeds.tbl_posts.link
FROM tbl_tags
INNER JOIN feeds.tbl_posts
ON tbl_tags.fd_postid=feeds.tbl_posts.fd_postid
ORDER BY tbl_tags.tag_name
It queries both Feeddemon’s tags.fdb primarily and attached feeds.fdb database files (using SQLite’s feature ATTACH feeds.fdb AS feeds). It lists all tagged posts with their tag names and hyperlinks. As you can see, the database content is related by fd_postid.
An example to visualize what happens:
tags.fdb‘s tbl_tags table content:
fd_postid tag_name
1 rainbow
2 orange
5 green
feeds.fdb‘s tbl_posts table content:
fd_postid link
1 google.com
2 stackoverflow.com
3 microsoft.com
4 slashdot.org
5 techcrunch.com
Query results, ordered by tag_name:
green techcrunch.com
orange stackoverflow.com
rainbow google.com
Question
How do I implement this single inner join query to cover multiple related databases, using PDO in PHP?
Connecting to two databases in PDO also creates two objects:
$db1 = new PDO('sqlite:tags.fdb');
$db2 = new PDO('sqlite:feeds.fdb');
But if I want to query, I have to specify a single object:
$result = $db1->query('SELECT * FROM sometable');
So how do I bridge the gap and use one query to target both databases?
Or can I use SQLite’s ATTACH database AS alias feature directly in PDO? If so, how? But this would probably be considered bad practice, right? Since PDO is intended to be database non-specific.
I think this user was looking for the same thing, in the end, but never really got to the point of a working code sample:
How do you join two PDO objects in the same foreach loop?
Note: When answering please consider the fact that I’m a front-end/graphics guy, who just started learning PHP/PDO/SQLite since about two months ago. The question is probably above my experience level. I’m surprised I managed to get the raw query working. But I’m learning…
To access multiple databases from one query in SQLite, you have to
ATTACHthem.With PDO, it works in same way as you would execute any other SQL command; you just specify a different file name (and directory, if needed):
While PDO is intended to be mostly independent of the actual database, you cannot avoid specifying the
sqlite:when opening the database, and the actual SQL dialect you can use always depends on the database. For practical purposes, theATTACHcommand is logically part of opening the database, andfeeds.tbl_postsis just a table name.Note: SQLite searches for table names in all attached databases, so you can omit the database name for unique table names.