2013-10-31 65 views
2

我想從mysql_ *切換到mysqli_ *,因爲一旦讀取,很快mysql_ *將不再受支持。從mysql切換到mysqli未定義變量:連接

現在我有一個問題,我寫的功能不工作了。

在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']; 
    } 

,但我得到以下錯誤:

Undefined variable: connect

應該是什麼我做? mysqli_query的工作方式除了functions.php文件以外。

回答

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

你正在做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']; 
}