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

I apologize if this has been asked before. I can not ask the question properly then.

I am getting an error on the "bindParam" that states $tools is undefined. I am unsure since I am still new too PHP. I am confused how or why it is out of scope. I am not sure because it is an object or what.

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

Also, Without the if(isset($db) under the include(connection.php') that shows up as if it is undefined.

Any suggestions or links would be greatly appreciated. please.

You made a mistake to use a if statement. The if statement without curly braces {} then statement only after the "if" condition get affected.

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();
}