好的,我看到一些与我类似的问题,但他们的示例都使用 PHP 类......我的没有。也许这就是问题所在?我不应该需要课程,因为此时我的网站非常简单。
无论如何,我正在尝试使用 PDO 连接到 MySQL 数据库。我在一个名为config.php
.index.php
require_once()
我可以从另一个名为 的文件中成功查询数据库process.php
,但问题出在该文件中的函数内;看来我的 DBO 对象超出了该函数的范围。
以下是相关的代码片段:
索引.php
require_once('./lib/config.php');
配置文件
// tested and connects fine
$pdo = new PDO('mysql:host=' . $hostname . ';dbname=' . $dbname, $username, $password, array(
PDO::ATTR_PERSISTENT => true
));
进程.php
<?php
...
// can call $pdo fine in this file outside of functions
...
function authenticate($u, $p) {
// can't call $pdo in here, error says $pdo is non-object
$que = $pdo->query('select user_id, user_pass from users where user_name = \'' . $u . '\' limit 1');
...
}
?>
顺便说一句,我使用 PDO 是因为我遇到了类似的问题mysqli
,并且正试图摆脱mysql
,这显然已被贬低和劝阻。
编辑:我应该首先根据我在这个问题上得到的回复数量进行澄清:我确实尝试将 $pdo 作为参数传递给函数,但没有运气或错误消息发生变化。
解决方案:好的,显然问题是我还需要require_once('config.php')
在我的process.php文件中添加。不知道为什么(第一次运行index.php时不会包含它吗?)。然后我能够成功地将$pdo
参数作为参数传递给我的函数,瞧。