2016-09-07 61 views
0

我無法將db連接到函數中:db連接丟失到函數中。 錯誤:mysqli_query()預計參數1是mysqli的,空給出將db連接到函數中

$dbcon = mysqli_connect($db_server, $db_user, $db_passwd); 

/* check connection */ 
if ($dbcon->connect_errno) { 
    printf("Connect failed: %s\n", $dbcon->connect_error); 
    exit(); 
} 

mysqli_select_db($dbcon,$db_name); 

function news() 
{ 

    $numPosts = mysqli_query($dbcon, 'SELECT count(*) as total FROM ' . $db_prefix . 'news'); 
} 

預先感謝您

回答

1

可以稍微重寫你的函數訪問$ dbcon作爲一個全局變量:

function news() { 

    global $dbcon; 

    $numPosts = mysqli_query($dbcon, 'SELECT count(*) as total FROM ' . $db_prefix . 'news'); 

} 

或將其作爲參數傳遞給news():

function news($dbcon) { 

    $numPosts = mysqli_query($dbcon, 'SELECT count(*) as total FROM ' . $db_prefix . 'news'); 

}