Reputation: 437
So part of my layout for my theme needs to query a database other than the database made for wordpress. I figured I would query the other database like normal. I wrote a quick function to take care of it:
function my_function() {
$con = mysql_connect("localhost", "user", "password");
mysql_select_db("database", $con);
$result = mysql_query("my query");
mysql_close($con);
$all = array();
while ($all[] = mysql_fetch_assoc($result)) {}
return $all;
}
I'm referencing the function in my header and realized it is breaking the categories in my sidebar. What's going on? I closed the connection I thought. What am I doing wrong? The error I get for the categories is this:
Warning: mysql_error(): 14 is not a valid MySQL-Link resource in /blog/wp-includes/wp-db.php on line 1098
Upvotes: 2
Views: 10992
Reputation: 1986
Is your custom database on the same mysql as the wordpress database? Then you can still use the $wpdb object:
global $wpdb;
$wpdb->get_results( "SELECT * FROM brian_db.brian_table" );
Even if you can't do that, I'd still recommend using the Wordpress Database class for the sake of consistency, you can set up a new connection in that function:
$wpdb_b = new wpdb( "user", "password", "brian_db", "localhost" );
$wpdb_b->get_results( "SELECT * FROM brian_table" );
update: corrected "global"
Upvotes: 12