PDO 不在函数内工作
我正在尝试创建一个函数,使用 PDO 准备语句从 MySQL 表中提取页面内容。我的代码在我定义的函数之外工作得很好,但无论我做什么,它都无法在函数内工作 - 我收到以下错误:
致命错误:在非-上调用成员函数prepare()第 6 行 /home/tappess1/public_html/pages/stations.php 中的对象
这是我的 PHP:
function getPageContent($page) {
$st = $db->prepare("SELECT * FROM content WHERE title LIKE ?");
$st->execute(array($page));
$pageContent = $st->fetch();
$text = wordwrap($pageContent['content'], 100, "\n");
$tabs = 4;
$text = str_repeat(chr(9), $tabs) . str_replace(chr(10), chr(10) . str_repeat(chr(9), $tabs), $text);
echo $text;
}
然后
<?php getPageContent(Main);?>
我什至尝试使用查询而不是准备语句,只需调用 getPageContent() 即可收到相同的结果错误。
谢谢!
I am trying to make a function to pull a page's content from a MySQL table using a PDO Prepare statement. My code works just fine outside of the function I defined, but no matter what I do it will not work within the function - I receive the following error:
Fatal error: Call to a member function prepare() on a non-object in /home/tappess1/public_html/pages/stations.php on line 6
Here is my PHP:
function getPageContent($page) {
$st = $db->prepare("SELECT * FROM content WHERE title LIKE ?");
$st->execute(array($page));
$pageContent = $st->fetch();
$text = wordwrap($pageContent['content'], 100, "\n");
$tabs = 4;
$text = str_repeat(chr(9), $tabs) . str_replace(chr(10), chr(10) . str_repeat(chr(9), $tabs), $text);
echo $text;
}
and then
<?php getPageContent(Main);?>
I have even tried using a query instead of prepare statement, simply calling getPageContent() and I receive the same error.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在尝试访问函数 范围。
在函数
$db = new PDO....
中重新初始化数据库,或者 - 在您的情况下可能更好、更容易 - 导入全局变量:在何处以及如何最好地存储全局数据库对象是很多讨论的主题。如果您想深入了解,这里是一个起点(SO 上还有很多其他地方)。但如果您刚刚接触 PHP,我认为使用全局变量就可以了。
You are trying to access the variable
$db
which is outside your function's scope.Either re-initialize your database within the function
$db = new PDO....
, or - probably better and easier in your case - import the global variable:Where and how to best store the global database object is subject of a lot of discussion. If you want to get into it, here is one place to start (there are many others on SO, too). But if you're just getting into PHP, I'd say using the global variable is fine.
变量 $db 在您的函数中未知。
The variable $db is not known within your function.