php5的mysqli函数第二个参数,关于php:我应该将$ mysqli变量传递给每个函数吗?
我從mysql_ *傳遞到面向?qū)ο蟮膍ysqli時(shí)遇到了一些問題。
我的index.php文件的結(jié)構(gòu)類似于包括兩個(gè)文件:
include('connect.php');
include('function.php');
connect.php文件包含:
$mysqli = new mysqli("localhost","root","test","test");
if (mysqli_connect_errno($mysqli)) {
printf("Connection failed: %s
", mysqli_connect_error());
exit();
}
?>
在function.php文件中,有一個(gè)名為showPage的函數(shù),該函數(shù)不帶任何參數(shù),但使用$ mysqli連接,例如...
$result = $mysqli -> query("SELECT * FROM $table ORDER BY ID DESC"); // Seleziono tutto il contenuto della tabella
我無法管理它而無法將$ mysqli變量傳遞給函數(shù),但是當(dāng)我使用mysql_ *不推薦使用的函數(shù)時(shí),這不是必需的!
我能理解為什么嗎,什么是解決此問題的最佳方法?
@Wired刪除密碼后,然后可能仍然使用它
如前所述,它是一個(gè)舊數(shù)據(jù)庫(也在本地),我正在對其進(jìn)行測試。 但是我還是不希望我的數(shù)據(jù)寫在網(wǎng)上= P還是讓我感到困擾
用戶定義的函數(shù)在PHP中具有自己的變量范圍。您需要將$mysqli作為參數(shù)傳遞給該函數(shù),或者使用global $mysqli啟動(dòng)該函數(shù)。
在"變量作用域"頁面上,給出了確切的問題作為示例:
However, within user-defined functions a local function scope is
introduced. Any variable used inside a function is by default
limited to the local function scope. For example, this script will not
produce any output because the echo statement refers to a local
version of the $a variable, and it has not been assigned a value
within this scope. You may notice that this is a little bit different
from the C language in that global variables in C are automatically
available to functions unless specifically overridden by a local
definition. This can cause some problems in that people may
inadvertently change a global variable. In PHP global variables must
be declared global inside a function if they are going to be used in
that function.
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
全局變量是邪惡的xD,但是您的答案是最好的。 我習(xí)慣了C,這就是為什么我無法做到這一點(diǎn)。 我更喜歡每次都將變量作為參數(shù)傳遞。 謝謝。
在這種情況下,全局變量是完全有效且可理解的設(shè)計(jì)模式。 畢竟,數(shù)據(jù)庫連接對象是應(yīng)用程序中的全局對象。 但是,我會(huì)將您的mysqli對象包裝在您自己的用戶創(chuàng)建的對象中,并在全局范圍內(nèi)使用此對象,因?yàn)檫@將使您能夠靈活地根據(jù)需要進(jìn)行改進(jìn)/升級(jí),而不必對應(yīng)用程序進(jìn)行大量更改。
您還可以使用連接池,值得一試。
$mysqli = new mysqli('p:localhost', 'username', 'password', 'db_name');
cannot manage it to work without passing to the function the $mysqli variable, but this was not necessary when I used mysql_* deprecated functions!
那是不正確的。即使在舊的mysql_*函數(shù)中,如果您需要指定與哪個(gè)數(shù)據(jù)庫連接有關(guān),實(shí)際上也必須傳遞鏈接標(biāo)識(shí)符,例如:
$result = mysql_query($sql, $link);
此示例還顯示了,您也必須傳遞$result。如果確實(shí)遺漏了$link參數(shù):
$result = mysql_query($sql);
mysql擴(kuò)展確實(shí)在內(nèi)部尋找上次使用的連接。如果沒有找到,它將使用php.ini中設(shè)置的參數(shù)創(chuàng)建一個(gè)新的。這只是為了您提供信息,以便更好地了解過去的原因和工作方式。
經(jīng)過更好的搜索后,我找到了答案,它適用于可能需要它的任何人:
PHP更改為mysqli。 mysqli_connection是否不是全局的?
這就是我需要的答案。無論如何,感謝所有幫助我的人
總結(jié)
以上是生活随笔為你收集整理的php5的mysqli函数第二个参数,关于php:我应该将$ mysqli变量传递给每个函数吗?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iis php json文件,配置iis
- 下一篇: Oracle数据库迁移后变慢,迁移数据之