Undefined Variable Error While Calling a Function

This question already has an answer here:

  • Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?

    3 answers

I’m working on an online store with PHP and in for this project I have made a db with some custom tables such as Brands, Categories, …

Then in order to retrieve data from db, I made this connect.php file which goes like this:

<?php 
$con = mysqli_connect("localhost","root","","myshop");
?>

After that I created a new file called get_cats.php which gets data from categories table:

    <?php 
require ('connect.php');
function get_cats(){
    $get_cats = "select * from categories";
    $run_cats = mysqli_query($con,$get_cats);
    while($row_cats=mysqli_fetch_array($run_cats)){
        $cat_id = $row_cats['cat_id'];
        $cat_title = $row_cats['cat_title'];
        echo "
            <div class='panel panel-default'>
                <div class='panel-heading'>
                    <h4 class='panel-title'><a href='index.php?cat=$cat_id'><strong>$cat_title</strong></a></h4>
                </div>
            </div>
        ";
    }
}
?>

Then at my index.php file I simply called the function:

<h2 class="BTitrBold">Categories</h2>
<div class="panel-group category-products BHoma" id="accordian">
<?php get_cats(); ?>
</div><!--/category-products-->

But whenever I load the page I get this error message:

Notice: Undefined variable: con in get_cats.php on line 5

And line 5 of get_cats.php is this:

$run_cats = mysqli_query($con,$get_cats);

However as you can see in the codes, I have correctly included the db connection file in this file. So I don’t know why I receive this error!

So if you know, please let me know.. I really appreciate that. Thanks 🙂

Add global $con; to your function. It is a global variable and is not automatically accessible by your function.