0

I am using Wordpress as a CMS for a bus-route planner, I have inputted the first few bus stops for the first bus route and am now developing a PHP script for the planner.

I am using this code, with a plugin that allows the use of PHP in Wordpress pages (providing they're surrounded with the [php] [/php] tag):

[php]
    if (mysqli_connect([db details removed]))
    {
        echo 'Connected to database!';
    } else {
        echo "Failed to connect!";
    }
[/php]

The result of implementing this connection is that the page 'crashes': it displays nothing, but has the page title:

enter image description here

Without the mysqli_connect, the page looks like this:

enter image description here

Yes, it may have a few formatting errors, but that's not the point here.

Why is Wordpress 'crashing' client-side when I attempt to connect to a MySQL database? For the record, the database is separate from the one Wordpress uses; perhaps Wordpress doesn't allow connecting to two different databases at the same time?

Furthermore, how can I connect to my MySQL database properly without causing this 'crash'?

  • 1
    I'm betting it's the plugin, just use a custom template (codex.wordpress.org/Templates) and assign that page to it if you need to execute arbitrary php. WordPress is not restricting you from connecting to another database. Edit: Though, you might consider consolidating them, WordPress has some good db connecting/interaction wrappers in the wpdb class so you can avoid doing all the legwork yourself. – Andrew Bartel Sep 24 '14 at 20:23
  • @AndrewBartel Actually turned out to be a typo, but however I used ialocin's method just to be safe. – AStopher Sep 24 '14 at 21:47
2

Firstly, you could and should use wpdb to connect to another database. E.g. like this:

$the_other_db = new wpdb(
    'username',
    'password',
    'database',
    'localhost'
);
$results = $the_other_db->get_results( $sql );

Take a look at Using wpdb to connect to a separate database for more information.

Secondly, like @AndrewBartel said it's likely the plugin. Besides IMHO - not insult intended - inputting PHP code like this into the templating area will always be pretty awful. So going with a custom template and some class(es) and/or function(s) for your functionality would just be the much better approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.