函数中的 Mysqli 查询 - PHP

2021-12-25 00:00:00 php mysqli

我在 functions.php 中有一个函数列表.我正在从 Mysql 升级到 Mysqli 因为我刚刚学习的 Mysql 现在已经贬值了.

I have a list of functions in functions.php. I'm upgrading from Mysql to Mysqli because I just learning Mysql is now depreciated.

我在顶级connect.php 文件中声明了我的连接.需要第一个文件.

I declare my connection in a top levelconnect.php file. The first file required.

无论如何回到我所有的函数都使用 mysql_query("QUERY") 并且总是工作正常的点.现在我将它们全部更改为:

Anyway back to the point all my functions use mysql_query("QUERY") and that always worked fine. Now I changed all them to:

$con->query("QUERY") // ($con is my connection variable)

现在我得到一个

致命错误:在第 241 行调用 C:wampwwwPHPfunctions.php 中非对象的成员函数 query()

Fatal error: Call to a member function query() on a non-object in C:wampwwwPHPfunctions.php on line 241

如果我在整个文件中声明我的变量,我不明白为什么我可以查询.它应该可以在任何地方访问,我只是不确定.这使我的网站暂停,直到我能解决这个问题.这是来自 functions.php

I don't get why I can query if I'm declaring my variable in my whole file. It should be accessible everywhere, I'm just not sure. This has put my website on hold until I can fix this. Here is a sample function from functions.php

function getSiteName()
{
    $row = $con->query("SELECT * FROM siteinfo")->fetch_array();
    return $row["siteName"];
}

我的连接:

global $con ;
$con = new mysqli("localhost", "itunes89", "XXXX","projectanvil") or die("Sorry, were having server connection issues. Please try again later.");

推荐答案

那是一个 变量作用域问题.您需要将 $conn 传递给 getSiteName():

That's a variable scope problem. You need to pass $conn to getSiteName():

function getSiteName($con) {
    $row = $con->query("SELECT * FROM siteinfo")->fetch_array();
    return $row["siteName"];
}

$name = getSiteName($con);

或者使用带有构造函数注入的类:

Or using a class with constructor injection:

class MyThing
{
    protected $con;

    public function __construct($con) {
        $this->con = $con;
    }

    public function getSiteName() {
        $row = $this->con->query("SELECT * FROM siteinfo")->fetch_array();
        return $row["siteName"];
    }
}

$obj = new MyThing($con);
$name = $obj->getSiteName();

在整个课程中,您可以使用 $this->con 来访问连接.

Throughout the class you can use $this->con to access the connection.

相关文章