Use $DB to query neighbor database on same server/connection

Use $DB to query neighbor database on same server/connection

by Frank Troglauer -
Number of replies: 2

Good morning,


I am wondering if it would be possible to use $DB to query a database outside of the Moodle one but on the same server? The only thing that would change in regards to the connection information would be the database name. So instead of moodle.mdl_users it would be neighbor.table. 


I know I can create a script on the server with the connection information and use a mysqli_connection to create a new connection but I would prefer to use the Moodle database query system if possible. 

Average of ratings: -
In reply to Frank Troglauer

Re: Use $DB to query neighbor database on same server/connection

by Mark Johnson -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Don't mess with the $DB global (you will break things), but you can create an instance of the moodle_database class (or an appropriate subclass like mysqli_native_moodle_database) and use that to query other databases. 

Perhaps something like this:

$extdb = new mysql_native_moodle_database(true); // true says that it's an external database, so don't use Moodle's prefix
$extdb->connect($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, 'neighbor', '');


Average of ratings: Useful (3)
In reply to Mark Johnson

Re: Use $DB to query neighbor database on same server/connection

by Frank Troglauer -

Hey Mark,

Thanks for the swift reply. This suggestion works splendidly. The only thing I had to change was on the first line of the sample code I added i to the mysql_native_moodle_database so it is instead mysqli_native_moodle_database. 


Thanks!