dongsi4547
2018-01-01 11:20
浏览 99
已采纳

使用从另一个php文件的php文件中定义的函数时出错

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?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题