通过在两者之间使用mysql_query和mysql_fetch_array命令调用下面的函数,连接和关闭数据库是否有任何问题
<?php function dbconnect() { $sql = "localhost"; $username = "------"; $password = "-----"; $connection = mysql_connect($sql, $username, $password) or die("unwable to cct"); $databse = mysql_select_db("-------", $connection); global $connection; } function close() { global $connection; mysql_close($connection); } dbconnect(); $query = "Some SQL Statement"; $data = mysql_query($query, $connection); - L1 while (mysql_fetch_assoc($data)) { //echo something } close(); ?>
目前,我收到一个错误消息,说L1的$ connection必须是一种资源,但它是BOOL。如果我在此处给出一条死亡声明,则会触发同样的情况。我不知道怎么了。请找出所有可能的错误。我不得不从编码中休假,过了一会儿我又回来了。
感谢和问候
在 分配变量 之前, 必须使用global关键字。否则,您可以在函数内部声明一个局部变量,然后调用对尚不存在的global的引用。在其他功能中,使用了不存在的全局变量。 __$connection``$connection``$connection
global
$connection``$connection``$connection
function dbconnect() { // Global first to be sure the subsequent $connection is the global // rather than a new one local to this function global $connection; $sql = "localhost"; $username = "------"; $password = "-----"; // Now this modifies the global $connection $connection = mysql_connect($sql, $username, $password) or die("unwable to cct"); $databse = mysql_select_db("-------", $connection); }
更具可读性的是使用$GLOBALS数组:
$GLOBALS
function dbconnect() { $sql = "localhost"; $username = "------"; $password = "-----"; // Using the $GLOBALS superglobal array $GLOBALS['connection'] = mysql_connect($sql, $username, $password) or die("unwable to cct"); $databse = mysql_select_db("-------", $GLOBALS['connection']); }
最好的办法是$connection从dbconnect()其他函数中返回并使用该值:
$connection
dbconnect()
function dbconnect() { $sql = "localhost"; $username = "------"; $password = "-----"; $connection = mysql_connect($sql, $username, $password) or die("unwable to cct"); $databse = mysql_select_db("-------", $connection); // Return from the function return $connection; } // call as $connection = dbconnect(); // and define your other functions to accept $connection as a parameter