PHP PDO 问题
我在网站框架中设置 PDO 时遇到问题。
我在“system.php”中打开我的连接,该连接包含在每个页面的开头
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass,
array( PDO::ATTR_PERSISTENT => true));
}
catch(PDOException $e) {
echo $e->getMessage();
}
,并在同一个文件(system.ph)上使用此代码,我在下面将其称为:
$STH = $DBH->query('SELECT value FROM settings WHERE type="theme"');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
define('THEME', 'themes/'.$row['value'].'/');
}
效果非常好!
但是,当我在 "default.php"
(包含在文件中)上调用与上面相同的查询时,它会返回:
Notice: Undefined variable: DBH in /pages/default.php on line 15
Fatal error: Call to a member function query() on a non-object
in /pages/default.php on line 15
我在这里做错了什么?
默认.php
<?php
$STH = $DBH->query('SELECT value FROM settings WHERE type="theme"');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) { echo $row['value']; }
?>
I'm having trouble setting up PDO in my website framework.
I open my connection in "system.php" which is included at the beginning of every page with this code here
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass,
array( PDO::ATTR_PERSISTENT => true));
}
catch(PDOException $e) {
echo $e->getMessage();
}
and on the same file (system.ph) I call this below it:
$STH = $DBH->query('SELECT value FROM settings WHERE type="theme"');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) {
define('THEME', 'themes/'.$row['value'].'/');
}
Which works perfectly!
However, when I call the same query as above on "default.php"
(which is included in the file) it comes back with:
Notice: Undefined variable: DBH in /pages/default.php on line 15
Fatal error: Call to a member function query() on a non-object
in /pages/default.php on line 15
What am I doing wrong here?
default.php
<?php
$STH = $DBH->query('SELECT value FROM settings WHERE type="theme"');
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetch()) { echo $row['value']; }
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果它在函数内部,
则在调用 query() 函数之前添加到该函数中。
If it is inside a function add
in the function before calling the query() function.
无论出于何种原因,该文件似乎都没有包含在 default.php 中。是否有引导程序在加载
default.php
之前为您执行包含操作?另外,请确保加载
default.php
的路径上没有出现错误。在我看来,如果出现异常,$DBH
将是未定义的。您是否在某个地方使用了输出缓冲,在看到异常的回显之前可能会清除该缓冲?您可能需要考虑将异常记录到文本文件中,以便输出缓冲不会阻止您看到正在发生的错误。Seems like that file isn't getting included in default.php for whatever reason. Is there a boot strapper someplace that does the including for you before
default.php
is loaded?Also, make sure that you're not getting an error on the path that loads
default.php
. It seems to me that$DBH
would be undefined if there were an exception. Are you using output buffering someplace that might be cleared before you can see the echoing of the exception? You may want to consider logging your exceptions to a text file instead so that output buffering doesn't prevent you from seeing the errors which are occurring.