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条回答 默认 最新

  • doumisha5081 2018-01-01 11:33
    关注

    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"); ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?