“注意:未定义的变量:db”当使用PDO时 [英] "Notice: Undefined variable: db" when using PDO
本文介绍了“注意:未定义的变量:db”当使用PDO时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ b
$ sql ='选择*类别ORDER BY order_cat在我学习PDO的过程中,我写了这段代码: DESC;
foreach($ db-> query($ sql)as $ row)
{
echo'< input type ='radio'name ='category'value ='$ row [ id]'> $ row [name]< br />;
}
然后我将它封装到如下的函数中:
函数GetCategory()
{
$ sql ='SELECT * FROM category ORDER BY order_cat DESC';
foreach($ db-> query($ sql)as $ row)
{
echo'< input type ='radio'name ='category'value ='$ row [ id]'> $ row [name]< br />;
我这样称呼:
echo GetCategory();
然而,当我这样做时,我得到这些错误:
注意:未定义变量:
db
致命错误:在非对象
$ b上调用成员函数 query()
$ b
我不知道我错过了什么;我在我的配置文件中声明了 $ db
,如下所示:
$ db = new PDO(mysql:host = $ localhost; dbname = $ namedb; charset = utf8,$ userdb,$ passdb);
解决方案
。
函数GetCategory()
{
global $ db;
...
}
如果之前已经定义过。 ..
On my quest to learn PDO, I wrote this code:
$sql = 'SELECT * FROM category ORDER BY order_cat DESC';
foreach ($db->query($sql) as $row)
{
echo "<input type='radio' name='category' value='$row[id]'>$row[name]<br />";
}
I then encapsulated it into a function like so:
function GetCategory()
{
$sql = 'SELECT * FROM category ORDER BY order_cat DESC';
foreach ($db->query($sql) as $row)
{
echo "<input type='radio' name='category' value='$row[id]'>$row[name]<br />";
}
}
I call it like this:
echo GetCategory();
However, when I do that, I get these errors:
Notice: Undefined variable:
db
Fatal error: Call to a member functionquery()
on a non-object
I don't know what I'm missing; I'm declaring $db
in my configuration file like so:
$db = new PDO("mysql:host=$localhost;dbname=$namedb;charset=utf8", $userdb, $passdb);
解决方案
Make the $db global as you are inside a function.
function GetCategory()
{
global $db;
...
}
If it has been defined before of course...
这篇关于“注意:未定义的变量:db”当使用PDO时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文