問題描述
我在 functions.php 中有一個函數(shù)列表.我正在從 Mysql 升級到 Mysqli 因為我剛剛學習的 Mysql 現(xiàn)在已經(jīng)貶值了.
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.
無論如何回到我所有的函數(shù)都使用 mysql_query("QUERY") 并且總是工作正常的點.現(xiàn)在我將它們?nèi)扛臑?
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)
現(xiàn)在我得到一個
致命錯誤:在第 241 行調(diào)用 C:wampwwwPHPfunctions.php 中非對象的成員函數(shù) query()
Fatal error: Call to a member function query() on a non-object in C:wampwwwPHPfunctions.php on line 241
如果我在整個文件中聲明我的變量,我不明白為什么我可以查詢.它應該可以在任何地方訪問,我只是不確定.這使我的網(wǎng)站暫停,直到我能解決這個問題.這是來自 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);
或者使用帶有構造函數(shù)注入的類:
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.
這篇關于函數(shù)中的 Mysqli 查詢 - PHP的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!