php执行变量undefined在try块中设置prepare语句

时间:2018-01-04 04:31:57

标签: php mysql pdo

如果之前有人问过,我道歉。我不能正确地问这个问题。

我在声明$tools is undefined的“bindParam”上收到错误。我不确定,因为我还是新的PHP。我很困惑它是如何或为什么超出范围。我不确定,因为它是一个对象或什么。

function query_group_by_param($param) {
try {
    include('connection.php');
    if(isset($db))
        $tools = $db->prepare("SELECT t.t_id as id, t.item_code as code, t.item_name as name,
                                t.retail_price as retail, t.sale_price as price,
                                t.item_pieces as  pieces, t.qty as quantity,
                                t.sold as sold, t.description as description,
                                b.brand as brand, c.category as category,
                                tt.tool_type as sections,
                                i.image as image
                               FROM Tools as t
                               INNER JOIN Brands as b on t.b_id = b.b_id
                               INNER JOIN Categories as c ON t.c_id = c.c_id
                               INNER JOIN Images AS i ON t.t_id = i.t_id
                               LEFT OUTER JOIN Types AS tt ON t.tt_id = tt.tt_id
                               WHERE tt.tool_type = :tool");
    $tools->bindParam(':tool', $param, PDO::PARAM_STR, 15); 
    $tools->execute();

}catch (PDOException $e) {
    echo 'unable to retrieve data';
    echo $e->getMessage();
    exit();
}
$tool = $tools->fetchAll(PDO::FETCH_ASSOC);
$tools->closeCursor();
return $tool; 
}

此外,如果if(isset($db)下没有include(connection.php') 显示好像它是未定义的。

非常感谢任何建议或链接。请。

1 个答案:

答案 0 :(得分:1)

使用if语句时出错了。 if语句没有大括号{},只有在“if”条件受到影响后才会声明。

if(isset($db)) {
  $tools = $db->prepare("SELECT t.t_id as id, t.item_code as code, t.item_name as name,
                            t.retail_price as retail, t.sale_price as price,
                            t.item_pieces as  pieces, t.qty as quantity,
                            t.sold as sold, t.description as description,
                            b.brand as brand, c.category as category,
                            tt.tool_type as sections,
                            i.image as image
                           FROM Tools as t
                           INNER JOIN Brands as b on t.b_id = b.b_id
                           INNER JOIN Categories as c ON t.c_id = c.c_id
                           INNER JOIN Images AS i ON t.t_id = i.t_id
                           LEFT OUTER JOIN Types AS tt ON t.tt_id = tt.tt_id
                           WHERE tt.tool_type = :tool");
  $tools->bindParam(':tool', $param, PDO::PARAM_STR, 15); 
  $tools->execute();
}