函数下的错误注意:未定义的变量:pdo

时间:2018-07-12 21:53:26

标签: php

我已经使用PDO正确定义了数据库连接,并且它与脚本(但与function()一起)工作良好。在函数外部运行的任何查询都可以正常运行,但在函数内部返回

Notice: Undefined variable: pdo in E:\xampp\htdocs\flexicart\test.php on line 16

Fatal error: Uncaught Error: Call to a member function prepare() on null in E:\xampp\htdocs\flexicart\test.php:16 Stack trace: #0 E:\xampp\htdocs\flexicart\test.php(45): attrGroup('1') #1 {main} thrown in E:\xampp\htdocs\flexicart\test.php on line 16

我不明白我要去哪里。一切似乎都很好。即使在函数之外具有$ selectPro和$ pro_attr下变量的查询也能很好地工作。但是使用$ nameattrGroup则不是。 代码

<?php
$dbname = "flexicart";
$username = "root";
$password = "";
$dbhost = "localhost";
$dbport = "10832";

$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

date_default_timezone_set('Asia/Kolkata');

function attrGroup($id)
{
    $nameattrGroup = $pdo->prepare("select * from `attribute_groups` where atg_id = '$id'");
    $nameattrGroup-> execute();
    $nameattrGroup_res-> $nameattrGroup->fetch();
    return $nameattrGroup_res;
}

function patValue($id)
{
    $patValue = $pdo->prepare("select * from `product_attributes` where pat_id = '$id'");
    $patValue-> execute();
    $patValue_res = $patValue->fetch();
    return $patValue_res;
}
//echo "ok";

$selectPro = $pdo->prepare("select * from `products` where pro_id = 1");
$selectPro-> execute();
$selectPro_r = $selectPro->fetch();

echo "<h1>".$selectPro_r['pro_brand']."</h1>";
echo "<br />";

$pro_attr = $pdo->prepare("select * from `product_attributes` where pat_product = '$selectPro_r[pro_id]' group by pat_group");
$pro_attr-> execute();
//echo "select * from `product_attributes` where pat_product = '$selectPro_r[pro_id]' group by pat_group";

while($pro_attr_res = $pro_attr->fetch())
{
    //echo $pro_attr_res['pat_group'];echo "<br />";
    $nameattrGroup_res = attrGroup($pro_attr_res['pat_group']);
    echo $nameattrGroup_res['atg_name']."(".$pro_attr_res['pat_group'].")";echo "<br />---------------------<br />";

    $selectAttr = mysql_query("select * from `attributes` where atr_group = '$pro_attr_res[pat_group]'");
    while($selectAttr_res = mysql_fetch_assoc($selectAttr))
    {
        echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$selectAttr_res['atr_name'];

        $patValue = patValue($selectAttr_res['atr_id']);
        echo "@@@@@@@@@@".$selectAttr_res['atr_group']."####".$patValue['pat_value'];

        echo "<br /><br />";
    }

}

?>

0 个答案:

没有答案