PHP包含在wordpress中没有连接到外部数据库


PHP include within wordpress not connecting to an external database

我在wordpress帖子上包含一个PHP页面与wordpress插件,我包含的页面上的代码是:

$conn=mysql_connect("localhost","username","pass"); 
mysql_select_db("dbname",$conn);
if(!function_exists("ContactLookup")) {
    function ContactLookup($sequence) {
        global $conn;
        $sql="SELECT * from contacts where sequence = '".$sequence."' ";
        $rs=mysql_query($sql,$conn) or die(mysql_error());
        $result=mysql_fetch_array($rs);
        return $result;
    }
}

但是返回错误:

Warning: mysql_query() expects parameter 2 to be resource, null given in index.php on line 93
line 93 = $rs=mysql_query($sql,$conn) or die(mysql_error());

我不太确定为什么我收到这个错误,因为我已经把$conn作为一个全局变量在PHP函数,我已经测试了数据库连接工作良好

将$conn变量重命名为其他变量。
检查这个例子:

$mysqlConn = null;
function ConnectToMysql() {
    $mysqlConn=mysql_connect("localhost","username","pass") or die(mysql_error()); 
    mysql_select_db("dbname",$mysqlConn) or die(mysql_error());
}
if(!function_exists("ContactLookup")) {
    function ContactLookup($sequence) {
        global $mysqlConn;
        if(!$mysqlConn) ConnectToMysql(); // reconnect and reinit connection variable if somewhere it have been changed
        $sql="SELECT * from contacts where sequence = '".$sequence."' ";
        $rs=mysql_query($sql,$mysqlConn) or die(mysql_error());
        $result=mysql_fetch_array($rs);
        return $result;
    }
}

注:我知道我的答案并不高明。我不喜欢使用mysql_*命令。