We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 1208
    • 79 Posts
    Need to write many snippets using direct DB access. And got simple a question, I can’t find an answer to:
    what do I need to include in my snippet to use default MODx DB connection settings so I don’t need to write $modx->db->connect every time.
      • 28042 ☆ A M B ☆
      • 24,524 Posts
      If it’s the same database that MODx is using, you don’t have to connect at all, MODx is already connected when the snippet is processed.
        Studying MODX in the desert - http://sottwell.com
        Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
        Join the Slack Community - http://modx.org
        • 1208
        • 79 Posts
        Great.
        But what if the DB is different, but the server, username and password are the same?
          • 28042 ☆ A M B ☆
          • 24,524 Posts
          You have to explicitly connect to it, with the host and login information. It might be worth trying something like this:
          $modx->db->connect('localhost','dbname');

          The default parameters should work for the rest of it.

          See http://wiki.modxcms.com/index.php/API:DBAPI:connect
            Studying MODX in the desert - http://sottwell.com
            Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
            Join the Slack Community - http://modx.org
            • 22303 MODX Staff
            • 10,725 Posts
            Quote from: almaron at Apr 02, 2010, 11:34 PM

            Great.
            But what if the DB is different, but the server, username and password are the same?
            if that’s the case, why not just build your queries to reference the database name? If the user has access to the other database, this will work much more efficiently than creating another connection (which is btw, one of the most expensive operations MODx ever has to do, i.e. takes longer than any other operation in most cases).