我的问题是我在我的通用脚本代码中和我的一个函数中使用变量$ db。它的目的是成为用于MySQL连接的变量。我需要在函数内部写入一些数据到数据库。在我的脚本中,我不能假定现有的数据库连接将会打开,因此我打开一个新的连接并在函数退出之前关闭它。自从这样做以后,脚本运行后说我的MySQL引用不好/不存在,我得到一个错误。PHP,变量范围问题
我可以将它固定在我的核心代码中的唯一我使用变量$ db作为数据库连接的变量名称。我也在函数中使用相同的变量。我没有想到这会是一个问题,因为我不在函数的$ db前面使用global。这应该意味着我的函数中的$ db引用在私有函数中,但似乎是关闭了公共$ db的连接。
有什么想法?我的代码
片段:
database.php中
db_connect()
{
// open mysql db connection and return it;
}
db_close(&$db)
{
// close the passed by reference db connection
}
api.php
api_verify($keyid, $userid, $key)
{
// open a new db connection
$db = db_connect();
// check for errors. if any errors are found note them in the db
// close the db
db_close($db);
}
main.php
include api.php;
include database.php;
// open a connection to the db
$db = db_connect();
// pull a list of things to process from the db and move through them one at a time
// call api_verify() on each key before working through it's data.
db_close($db)
这取决于您的连接代码。如果实际上是从池中提供连接,并且其中一个内部方法关闭了连接,则外部方法之一所指向的连接可能会过时 – JohnP 2011-04-24 07:12:27
不要关闭连接...如果您打开一个新连接使用相同的参数,它只是重用已经打开的连接,所以如果你关闭了你的api函数中的连接,你可以在任何地方关闭它 - 即使你不通过引用 – prodigitalson 2011-04-24 07:15:14
为什么关闭连接? – zerkms 2011-04-24 07:16:18