Go to main content

Textpattern CMS support forum

You are not logged in. Register | Login | Help

#1 2021-06-20 05:19:35

Myusername
Member
Registered: 2019-12-12
Posts: 162

database swap shortcode

This shortcode changes the database temporarily for elements that are inside the container. It’s simple. It was useful for me, maybe it’s for someone too.

<txp:php>
    global $DB,$txpcfg;

    $old_txpcfg = $txpcfg;

    $txpcfg['db'] = parse('<txp:yield name="db"/>');
    $txpcfg['user'] = parse('<txp:yield name="user"/>');
    $txpcfg['pass'] = parse('<txp:yield name="pass"/>');
    $txpcfg['host'] = parse('<txp:yield name="host"/>');
    $txpcfg['table_prefix'] = parse('<txp:yield name="table_prefix"/>');

    $DB = new DB;

    echo parse('<txp:yield/>');

    $txpcfg = $old_txpcfg;
    $DB = new DB;
</txp:php>
<txp::db_swap db="" user="" pass="" host="" table_prefix="">
   <txp:article_custom>
        <h2><txp:title/></h2>
   </txp:article_custom>
</txp::db_swap>

Last edited by Myusername (2021-07-21 11:59:46)

Offline

#2 2021-06-20 06:54:57

Bloke
Developer
From: Leeds, UK
Registered: 2006-01-29
Posts: 11,271
Website GitHub

Re: database swap shortcode

Nice!

You could take this idea and improve its security by allowing someone to connect to the DB credentials from files that you pre-prepare.

For example, clone config.php to make a textpattern/config-alt.php file, change it to have the alternative credentials and then allow the shortcode to take one parameter: the file suffix that you append to config- in the shortcode:

<txp::db_swap name="alt">
// do something on alt db
</txp::db_swap>

That way, there are no credentials in articles/forms, and people can only connect to sources you pre-define in dedicated config files that begin with config-.

Just an idea. Thanks for sharing this fab tip.

Last edited by Bloke (2021-06-20 06:56:30)


The smd plugin menagerie — for when you need one more gribble of power from Textpattern. Bleeding-edge code available on GitHub.

Txp Builders – finely-crafted code, design and Txp

Offline

#3 2021-06-20 10:00:52

jakob
Admin
From: Germany
Registered: 2005-01-20
Posts: 4,596
Website

Re: database swap shortcode

Nice :-) This more or less replaces rah_swap, which also uses a similar idea of adding the alternative db connection credentials as separate arrays to config.php, avoiding the need for a separate file.


TXP Builders – finely-crafted code, design and txp

Offline

Board footer

Powered by FluxBB