php5的mysqli函数第二个参数,关于php:我应该将$ mysqli变量传递给每个函数吗?
我從mysql_ *傳遞到面向對象的mysqli時遇到了一些問題。
我的index.php文件的結構類似于包括兩個文件:
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文件中,有一個名為showPage的函數,該函數不帶任何參數,但使用$ mysqli連接,例如...
$result = $mysqli -> query("SELECT * FROM $table ORDER BY ID DESC"); // Seleziono tutto il contenuto della tabella
我無法管理它而無法將$ mysqli變量傳遞給函數,但是當我使用mysql_ *不推薦使用的函數時,這不是必需的!
我能理解為什么嗎,什么是解決此問題的最佳方法?
@Wired刪除密碼后,然后可能仍然使用它
如前所述,它是一個舊數據庫(也在本地),我正在對其進行測試。 但是我還是不希望我的數據寫在網上= P還是讓我感到困擾
用戶定義的函數在PHP中具有自己的變量范圍。您需要將$mysqli作為參數傳遞給該函數,或者使用global $mysqli啟動該函數。
在"變量作用域"頁面上,給出了確切的問題作為示例:
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,但是您的答案是最好的。 我習慣了C,這就是為什么我無法做到這一點。 我更喜歡每次都將變量作為參數傳遞。 謝謝。
在這種情況下,全局變量是完全有效且可理解的設計模式。 畢竟,數據庫連接對象是應用程序中的全局對象。 但是,我會將您的mysqli對象包裝在您自己的用戶創建的對象中,并在全局范圍內使用此對象,因為這將使您能夠靈活地根據需要進行改進/升級,而不必對應用程序進行大量更改。
您還可以使用連接池,值得一試。
$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_*函數中,如果您需要指定與哪個數據庫連接有關,實際上也必須傳遞鏈接標識符,例如:
$result = mysql_query($sql, $link);
此示例還顯示了,您也必須傳遞$result。如果確實遺漏了$link參數:
$result = mysql_query($sql);
mysql擴展確實在內部尋找上次使用的連接。如果沒有找到,它將使用php.ini中設置的參數創建一個新的。這只是為了您提供信息,以便更好地了解過去的原因和工作方式。
經過更好的搜索后,我找到了答案,它適用于可能需要它的任何人:
PHP更改為mysqli。 mysqli_connection是否不是全局的?
這就是我需要的答案。無論如何,感謝所有幫助我的人
總結
以上是生活随笔為你收集整理的php5的mysqli函数第二个参数,关于php:我应该将$ mysqli变量传递给每个函数吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iis php json文件,配置iis
- 下一篇: linux cmake编译源码,linu