Link to home
Start Free TrialLog in
Avatar of jazzviolin
jazzviolinFlag for China

asked on

PHP connect to MySQL database in Wordpress sidebar (widget)

I'm having trouble connecting to a database file using the "text/html" widget in Wordpress 2.8.4.  This is the widget that allows you to add text to a sidebar.  I found a plugin for including PHP in the code, but it didn't work.  (plugin: http://bit.ly/4QMCj)

The database file is at: http://www.mydomain.com/database/db.php
The WP blog is installed at  http://www.mydomain.com/blog/

The (truncated) code I'm using (which works on the HTML portion of the site) is below.

Is there a way to use absolute paths?
<?php
include '../database/db.php';
 
open_db();
 
}
 
close_db();
?>

Open in new window

Avatar of jazzviolin
jazzviolin
Flag of China image

ASKER

Could it be that the PHP that connects to the database cannot be inserted in the sidebar?  Does it need to go in another Wordpress file?
you should create a seperate file and place it under plugins directory to include your php scripts in the sidebar widget.

How to write a plugin - simple steps
http://codex.wordpress.org/Writing_a_Plugin

HTH,
~PG
Hi PG,

Do you mean, create a widget that includes the connection information to the database (user, pw, open, close, etc)?  I tried this, and it didn't work.

since wp is in folder http://www.mydomain.com/blog/, it never seen the directory above it; ie. http://www.mydomain.com/database/

to use mysql, you must have something like this
mysql_connect('host', 'username', 'password');
mysql_select_db('database');
The following is my db.php, which is located at mydomain.com/database/db.php

Again, the blog is mydomain.com/blog/

From my static site, it works.  From the Wordpress sidebar, I've tried a bunch of different things, but nothing works.  

1 - I've tried connecting to the db.com within the sidebar
2 - I've tried creating a new plugin, where the authentication was the plugin and activated it
<?php
$VARS = array();
$VARS['db_host'] = "host";
$VARS['db_user'] = "wayne";
$VARS['db_pass'] = "password1";
$VARS['db_name'] = "dbname";
 
$conn = null;
 
function open_db() {
	global $VARS, $conn;
	
	$conn = mysql_connect($VARS['db_host'], $VARS['db_user'], $VARS['db_pass']) or die ('Error connecting to mysql');
	mysql_select_db($VARS['db_name']) or die(mysql_error()); 
}
 
function close_db() {
	global $conn;
	
	mysql_close($conn);
}
 
?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of pg-expert
pg-expert
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial