从mysql切换到mysqli未定义变量:connect

时间:2013-10-31 23:32:35

标签: php mysqli

我想从mysql_*切换到mysqli_*,因为我已经读过,很快就会不再支持mysql_*

现在我遇到了一个问题,我写的功能不再适用了。

在index.php文件中我有

global $connect;
$connect = mysqli_connect('localhost', "username", "password");

并且在functions.php文件中我有

function count_total_messages(){
        $result = "SELECT COUNT(id) AS total FROM database.messages WHERE uidto='".$_SESSION['userid']."' OR unameto='".$_SESSION['username']."'";
        $qry = mysqli_query($connect,$result);
        return $qry['total'];
    }

但是我收到以下错误:

  

未定义的变量:connect

我该怎么办?除了来自functions.php文件的那些文件外,mysqli_query的所有地方都有效。

2 个答案:

答案 0 :(得分:5)

function count_total_messages(){
        global $connect;  //You need a locally defined connect variable
        $result = "SELECT COUNT(id) AS total FROM database.messages WHERE uidto='".$_SESSION['userid']."' OR unameto='".$_SESSION['username']."'";
        $qry = mysqli_query($connect,$result);
        return $qry['total'];
    }

答案 1 :(得分:1)

你正在以错误的方式做global。在您的索引中,您只需要

$connect = mysqli_connect('localhost', "username", "password");

在你的功能中你使用它:

function count_total_messages(){
    global $connect;
    $result = "SELECT COUNT(id) AS total FROM database.messages WHERE uidto='".$_SESSION['userid']."' OR unameto='".$_SESSION['username']."'";
    $qry = mysqli_query($connect,$result);
    return $qry['total'];
}