Go to main content

Textpattern CMS support forum

You are not logged in. Register | Login | Help

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

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.

    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::db_swap db="" user="" pass="" host="" table_prefix="">

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


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

From: Leeds, UK
Registered: 2006-01-29
Posts: 11,301
Website GitHub

Re: database swap shortcode


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

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


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

From: Germany
Registered: 2005-01-20
Posts: 4,633

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


Board footer

Powered by FluxBB