0

说,我有一个 php 文件functions.php,如下所示:

<?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");

?>

db_connect.php和另一个名为如下的 php 文件:

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

现在,我想使用get_option_list()另一个以以下方式命名的 php 文件my_view.php中的方法:

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

有了所有这些文件,每当我运行my_view.php文件时,我都会收到如下错误:

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

但是,当get_option_list()functions.php文件本身调用时,不会出现此类错误,我可以看到预期的输出。我怀疑我的代码中存在一些问题,无法处理从一个文件正确传递到另一个文件的值。任何人都可以在这里帮助我吗?

4

2 回答 2

0

您必须使用$db全局,但这不是一个好习惯。

 function get_option_list($table, $col_id, $col_value, $sel=0){
        global $db;
        $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;
    }

您可以使用 PHP 数据库库,例如MedooMeekroDB等...

否则,您必须$db作为参数传递。

get_option_list($db, $table, $col_id, $col_value, $sel=0)
于 2018-01-01T11:25:22.487 回答
0

get_option_list 方法没有传递 $db 值的参数。

你可以包括它:

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

然后通过它:

<?php echo get_option_list($db, "city","city_id","city_name"); ?>
于 2018-01-01T11:33:59.233 回答