How to simultaneously access the same MySQL database in the main column and sidebar of WordPress?

I’ve wrote some basic custom PHP code for my WordPress site. The code basically access a MySQL database (a different database from the wordpress database) and displays the information. In addition to running it on the main page, I also need it to run on the sidebar. The code functions perfectly in the main page or it functions perfectly in the sidebar, but when I put the code in both, I get the following error in the sidebar:

Fatal error: Call to a member function prepare() on a non-object in /home/kimusubi/public_html/wp-content/plugins/php-code-widget/execphp.php(44) : eval()’d code on line 5

Read More

I thought it was an issue of accessing the same table and database at the same time, but I’m using include_once and closing my connection as soon as I’m done with it, so I’m not sure what the problem is. This is the code that I’m using for the sidebar and the main column page:

<?php
include_once 'db_config.php'; //Include database configuration file
$current_user = wp_get_current_user()->user_login; //Get current WP logged in user
try { //Access accounts table and pull user info into associative array
    $STH = $DBH->prepare("SELECT * FROM accounts WHERE accnt = :accnt");
    $STH->bindParam(':accnt', $current_user);
    $STH->execute();
    $Result = $STH->fetch(PDO::FETCH_ASSOC);
    $DBH = null;
    }
catch(PDOException $e) {  
    echo "Select Accounts Table Error: " .$e->getMessage(). "</br>"; //Display Error (if any)
}

$available = min($Result['week_two'],$Result['week_one'],$Result['current']);

echo "Account: " .$Result['accnt']. "</br>";
echo "Name: " .$Result['first']. " " .$Result['last']. "</br>";
echo "Address: " .$Result['address']. ", " .$Result['city']. ", " .$Result['state']. ", " .$Result['zip']. "</br>";
echo "Phone: " .$Result['phone']. "</br>";
echo "Current Balance: $" .$Result['current']. "</br>";
echo "Available Balance: $" .$available. "</br>";
?>

And this is what’s in my db_config.php file:

<?php
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

}
catch(PDOException $e) {  
    echo "Select DB Error: " .$e->getMessage(). "</br>";
}

?>

Exec-PHP is the only plugin I’m using in order to execute PHP directly from WordPress. I’d appreciate any guidance.

Related posts

Leave a Reply

2 comments