gpt4 book ai didi

php - 使用 PDO 时为 "Notice: Undefined variable: db"

转载 作者:行者123 更新时间:2023-12-01 00:50:47 24 4
gpt4 key购买 nike

<分区>

为了学习 PDO,我写了这段代码:

$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 />";
}

然后我将它封装成一个函数,如下所示:

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 />";
}
}

我这样调用它:

echo GetCategory();

但是,当我这样做时,出现了这些错误:

Notice: Undefined variable: db
Fatal error: Call to a member function query() on a non-object

我不知道我错过了什么;我在配置文件中这样声明 $db:

$db = new PDO("mysql:host=$localhost;dbname=$namedb;charset=utf8", $userdb, $passdb);

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com