我有一个wordpress网站,我想在 functions.php
中保存并进行数据库连接所以我可以在我的模板中调用它。 以下是 functions.php
中的函数代码<?php
function dbconnd() {
$server = "localhost";
$duser = "wpuser";
$dpass = "wppass";
$dbname = "wpdb";
$conn = new mysqli($server, $duser,$dpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
?>
所以在我的main.php中,如果我调用dbconnd();
,它似乎无法正常工作,因为它会抛出致命错误,如下例所示:
致命错误:在非对象中调用成员函数query() 第49行的/main.php
<?php
dbconnd();
$sql = "SELECT * FROM orderform WHERE status='last';";
$result = $conn->query($sql); //this is line 49
?>
但是在下面的情况下,当我没有调用该函数时,它完美地运行
<?php
$server = "localhost";
$duser = "wpuser";
$dpass = "wppass";
$dbname = "wpdb";
$conn = new mysqli($server, $duser,$dpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM orderform WHERE status='last';";
$result = $conn->query($sql);
?>
答案 0 :(得分:0)
您现在的工作方式,$conn
只是函数内部的局部变量。所以你无法以这种方式获得函数之外的值。
最好的解决方案是:
function dbconnd() {
$server = "localhost";
$duser = "wpuser";
$dpass = "wppass";
$dbname = "wpdb";
$conn = new mysqli($server, $duser,$dpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
return $conn;
}
然后当你打算调用这个函数时,运行它:
$conn = dbconnd();
另外不要忘记在php文件中包含或要求functions.php文件调用它。