• Resolved jackennils

    (@jackennilsen)


    Hello!

    In my theme I’m using a instance of “wpdb” to get some values from a second non-WP database. As this data is needed in my single.php theme file, I also put the code to connect to this DB in the single.php.

    $phpbb_db = new wpdb('user','password','database_name','host');

    Is this okay in terms of security or should the credentials be put somewhere else?

    Thanks!

    //Nils

Viewing 7 replies - 1 through 7 (of 7 total)
  • Hi,

    Yes, it should be okay I think, though it’ll be a good idea to use connection details as constants defined somewhere in one place (e.g. functions.php), so you don’t have to define them multiple times.

    Thanks

    Thread Starter jackennils

    (@jackennilsen)

    I tried to put them in the wp-config.php, but how can I use them in the theme files?

    • This reply was modified 7 years, 9 months ago by jackennils.

    In wp-config you can set defines. They will be accesible everywhere without needing to use globals. Define something: define('MY_DEFINE_NAME', 'THE_VALUE');

    Then in your templates you can show the value like this: echo MY_DEFINE_NAME;

    Or set the value to a variable: $var = MY_DEFINE_NAME;

    Thread Starter jackennils

    (@jackennilsen)

    Thank you Pavel. That’s exactly what I have tried. But it didn’t work.

    I have put some defines in my wp-config:

    define('DB2_NAME', 'my_second_db_name');
    define('DB2_USER', 'my_second_db_user');
    define('DB2_PASSWORD', 'my_second_db_password');
    define('DB2_HOST', 'my_second_db_host');

    And then put them as variables in my theme:

    $db2_name = DB2_NAME;
    $db2_user = DB2_USER;
    $db2_password = DB2_PASSWORD;
    $db2_host = DB2_HOST;

    Finally tried to use them with wpdb:
    $second_db = new wpdb('$db2_user','$db2_password','$db2_name','$db2_host');

    What am I missing?

    I think you don’t need quotes in wpdb query, so instead of this:
    $second_db = new wpdb('$db2_user','$db2_password','$db2_name','$db2_host');

    it should look like this:
    $second_db = new wpdb($db2_user,$db2_password,$db2_name,$db2_host);
    because otherwise you pass strings instead of variables there.

    Thread Starter jackennils

    (@jackennilsen)

    That’s it! Thank you so much. You saved my day. ??

    You’re welcome! ??

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Where to put code for second DB connection?’ is closed to new replies.