从其他函数中的一个函数变量

时间:2015-03-15 08:39:42

标签: php mysqli

我有函数connect()

function connect(){
    $host = '';
    $name = '';
    $pass = '';
    $port = '';
    $db = '';
    $con = mysqli_connect($host,$name,$pass,$db,$port) or die (mysqli_connect_error());
    return $con;
}

我有功能check_exists

function check_exists($username){
    $num = mysqli_num_rows(mysqli_query($con,"SELECT * FROM `accounts` WHERE `user` = '$username'"));
    return $num;
}

但check_exists不知道变量$ con是什么。我怎样才能让check_exists知道$ con是什么?

2 个答案:

答案 0 :(得分:4)

您可以将$con传递给

这样的功能
 $con =  connect();
 check_exists($username,$con);

function check_exists($username,$con){
        $num = mysqli_num_rows(mysqli_query($con,"SELECT * FROM `accounts` WHERE `user` = '$username'"));
        return $num;
    }

答案 1 :(得分:-1)

那么你可以将$conn变量设为全局,或者你可以在check_username方法中调用连接函数$conn = $this.connect();