我在带有wordpress插件的wordpres帖子中包含一个PHP页面,我所包含的页面上的代码是:
$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函数中,并且我已经测试了数据库连接正常工作
答案 0 :(得分:0)
将$ 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;
}
}
P.S。我知道我的答案并不精彩。我不喜欢使用mysql_ *命令。但这是一个快速解决方案。