I need to execute this SQL query:
SELECT DISTINCT
logger.hcp_id,
logger.rep_id,
logger.type,
session_brand_presentation.ID,
session_brand_presentation.brand_id,
session_brand_presentation.createdAt,
session_brand_presentation.modifiedAt
FROM
archive_pfizer.logger
JOIN
pdone_legacy.session_brand_presentation ON logger.session_id = session_brand_presentation.local_session_id
WHERE
logger.type = 'email_sent';
As you may already notice I am querying to different databases: archive_pfizer
and pdone_legacy
. I know that DSN needs a DB name for create the PDO object then as title say: How do I execute a PDO statement when there are two databases involve in the same query?
Very important I am asking how to achieve this from PHP using PDO, I was able to execute the query successfully from MySQL/MariaDB command line and/or using any GUI.
UPDATE
Here is the code I was working on based on @RyanVincent answer:
$config = parse_ini_file('config.ini', true);
define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
$DBASE = $config['database']['DBASE'][0];
$pdo = setupDB($config, $DBASE);
$sql = 'SELECT DISTINCT logger.hcp_id, logger.rep_id, logger.type, session_brand_presentation.ID, session_brand_presentation.brand_id, session_brand_presentation.createdAt, session_brand_presentation.modifiedAt FROM archive_pfizer.logger JOIN pdone_legacy.session_brand_presentation ON logger.session_id = session_brand_presentation.local_session_id WHERE logger.type = "email_sent"';
foreach($pdo->query($sql) as $row) {
var_export($row);
echo EOL;
}
But I got this error:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'pdone_legacy.session_brand_presentation' doesn't exist'
Apparently it's taking pdone_legacy.session_brand_presentation
as a table when it's a database, in the example provided is the same as testmysql
, any advice?
UPDATE 2
Trying the same SQL query but using aliases didn't work either:
$sql = 'SELECT DISTINCT
lg.hcp_id,
lg.rep_id,
lg.type,
sbp.ID,
sbp.brand_id,
sbp.createdAt,
sbp.modifiedAt
FROM
archive_pfizer.logger AS lg
JOIN
pdone_legacy.session_brand_presentation AS sbp ON lg.session_id = sbp.local_session_id
WHERE
lg.type = "email_sent"';
Got exactly the same issue as before.
UPDATE 3
Ok, perhaps I will got killed after say this but was my bad all the time. I was connecting to a server where DB pdone_legacy
exists but that DB in fact hasn't session_brand_presentation
table and that is what PDO was saying all the time. Anyway thanks to anyone here and both queries are valid.