phpinclude-once

Getting error when using a function defined inside a php-file from another php-file


Say, I have a php-file named functions.php like below:

<?php

    include_once("db_connect.php");
    ### function to populate the City/State/Country drop-downs ###
    function get_option_list($table,$col_id,$col_value,$sel=0){
        $SQL = "SELECT * FROM $table";
        $rs = mysqli_query($db,$SQL) or die(mysqli_error());
        $option_list = "<option value='0'>Please select...</option>";
        while($data = mysqli_fetch_assoc($rs)){
            $option_list.= "<option value='$data[$col_id]'>$data[$col_value]
  </option>";
        }
        return $option_list;
    }

    //echo get_option_list("city","city_id","city_name");
    //echo get_option_list("state","state_id","state_name");
    //echo get_option_list("country","country_id","country_name");

?>

and another php-file named db_connect.php as below:

<?php
    $db = mysqli_connect("localhost","root","","sms1") or die(mysqli_connect_error());
?>

Now, I want to make use of the get_option_list() method from another php-file named my_view.php in the below manner:

<?php include_once("functions.php"); ?>
<form>
    <select>
    <?php echo get_option_list("city","city_id","city_name"); ?>
    </select>
</form>

Having all these files in place, whenever I'm running the my_view.php file, I'm getting errors like below:

Notice: Undefined variable: db in C:\xampp\htdocs\sms1\includes\functions.php on line 7
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\sms1\includes\functions.php on line 7
Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\sms1\includes\functions.php on line 7

But, when calling the get_option_list() from the functions.php file itself, no such errors appear and I can see the expected output. What I doubt is that there is some issue in my code which is not able to handle the value passing properly from one file to another. Can anyone please help me out here?


Solution

  • The method get_option_list has no parameter to pass the $db value.

    You could include it:

    function get_option_list($db, $table, $col_id, $col_value, $sel=0) {
    

    And then pass it:

    <?php echo get_option_list($db, "city","city_id","city_name"); ?>