我可以连接到php文件中的数据库,然后在包含的文件中进行查询,而不需要再次连接吗


Can I connect to a database in a php file, and then make queries in an included file without connecting again?

我想知道include文件的范围。我测试了它,但它没有工作,我不确定我的问题是范围。如果我能做到这一点,我会在其他方面寻找问题。

在父文件中

mysql_connect("ip and port","name","password"); 
mysql_select_db("fskea1");

在包含的文件中

mysql_query("select * from blabla).

给了我

警告:mysql_query(([function.mysql-query]:拒绝用户访问中的"ODBC"@"本地主机"(使用密码:NO(D: ''Home''fskea1.com''httpdocs''wquest''register.php第20行警告:mysql_query(([function.mysql-query]:无法链接到服务器在D:''Home''fskea1.com''httpdocs''wquest''register.php中建立20号线

更新:我尝试将连接添加到子include文件,现在它可以工作了。看起来,我需要连接到每个php文件中的数据库。

它应该可以工作——我自己为网页上的子表单做过。

如果包含的文件是使用include('xyz.php')导入的,那么它会正常工作。不确定它是否会通过readfile工作-从未尝试过。

是的,这是可能的。

您可能有可变范围的问题。有关更多信息,您需要显示一些代码。

这一直对我有效:

<?php
function openDB() {
    $link = $GLOBALS['link'];
    if (!isset($link)) $link= @mysql_connect( 'host', 'user', 'pw');
    if (!$link) {
        return 0;
    } elseif (!mysql_select_db('database-name', $link)) {
        return 0;
    } else {
        return $link;
    }
}
$link = openDB();

然后,在其他地方:

<?php
if (!$link) $link = openDB();
mysql_query("select * from blabla");