2013-07-21 71 views
-2

我是PDO的新手,所以很抱歉,如果這可能相當簡單,但我花了數小時試圖找到答案,因此不得不發佈。調用PDO查詢錯誤的函數

我有存儲在我的函數文件中的函數:

function insertlogs($user) 
     { 
    $page = basename($_SERVER['PHP_SELF']); 
    $ip = GetIP(); 
    $ub = getBrowser(); 
    $regdate = date("Y-m-d"); 
    $regtime = date("H:i:s"); 


       try{ 
        $sql = "INSERT INTO admin_logs (id, 
        page, 
        ip, 
        browser, 
        loggedinuser, 
        date, 
        time) VALUES (
        :gid, 
        :page, 
        :ip, 
        :ub, 
        :user, 
        :regdate, 
        :regtime)"; 

$stmt = $db->prepare($sql);   


$stmt->bindParam(':gid', $gid);  
$stmt->bindParam(':page', $page); 
$stmt->bindParam(':ip', $ip); 
$stmt->bindParam(':ub', $ub); 
$stmt->bindParam(':user', $user); 
$stmt->bindParam(':regdate', $regdate); 
$stmt->bindParam(':regtime', $regtime); 


$stmt->execute(); 



} 

catch(PDOException $e) { 
echo $e->getMessage(); 
}} 

當我運行這個獨立正常工作。但是,當我調用這個函數insertlogs($ user);它給了我致命錯誤:調用一個成員函數prepare()中的一個非對象....錯誤。

我檢查了連接,這似乎很好,我只是不知道嗎?任何幫助或指針將不勝感激。

+0

您確定'$ db'是一個PDO對象嗎? – Ohgodwhy

+0

你還沒有在任何地方定義'$ db'。 – PeeHaa

+0

該函數是否可以訪問'$ db'? – hjpotter92

回答

1

When I run this independently it works fine. However when I call this function insertlogs($user); Its gives me the Fatal error: Call to a member function prepare() on a non-object in.... error.

我想通過「我獨立運行」 - 你的意思是你運行的代碼超出了功能的範圍。當你把它作爲函數調用時,$ db是一個全局變量,php不知道它。並認爲,這是本地的,看2擋例子在這裏:

http://php.net/manual/en/language.variables.scope.php

所以,無論是將它作爲第二個變量(最好):

function insertlogs($user, &$db) 

或者使用全局:

function insertlogs($user) 
{ 
    global $db; 
+0

謝謝@ user4035。我應該知道更好的:) – skippy