2012-05-09 25 views
1

我試圖從一個PHP函數中執行SQL查詢,但我不斷收到以下錯誤:試圖從一個PHP函數中執行SQL查詢

Fatal error: Call to a member function prepare() on a non-object in /homepages/23/d363590707/htdocs/bNames.php5 on line 14

第14行與行在下面的方法制備方法:

function testing() 
{ 
    $query = "SELECT `no` FROM `brandNames` WHERE `id` = $index"; 
    $stmt = $dbc->prepare($query); <--- line 14 -----------------<<< 
    $stmt->execute(); 
    $stmt->store_result(); 
    $stmt->bind_result($no); 
    $stmt->fetch(); 
} 

注:當我堅持的代碼塊在頁面(不使用的函數)的查詢工作,我沒有任何問題。

另外,我打算爲這個函數添加參數來替換表名,列名和值。這只是一個最少量的可能出錯但仍然說明我的問題的版本。

在此先感謝

編輯:這是文件的樣子:

<?php 
    require_once('connectvars.php'); //contains the info used in mysqli_connect 

    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 


    function testing($dbc) 
    { 
     $query = "SELECT `no` FROM `brandNames` WHERE `id` = $index"; 
     $stmt = $dbc->prepare($query); 
     $stmt->execute(); 
     $stmt->store_result(); 
     $stmt->bind_result($no); 
     $stmt->fetch(); 
    } 

//more code 
?> 
+5

定義'$ dbc'在哪裏?看起來它超出了範圍。 –

+0

@GioBorje相信它在全球範圍內,我編輯我的OP,以顯示它看起來像 –

回答

4

雖然你可以定義$dbcglobal,我會建議只是傳遞$dbc進入功能:

function testing($dbc) 
{ 
    $query = "SELECT `no` FROM `brandNames` WHERE `id` = $index"; 
    $stmt = $dbc->prepare($query); <--- line 14 -----------------<<< 
    $stmt->execute(); 
    $stmt->store_result(); 
    $stmt->bind_result($no); 
    $stmt->fetch(); 
} 

現在,當你調用testing(),你需要在$dbc經過:testing($dbc);

+0

現在我在下一行(執行)出現錯誤。任何想法爲什麼會發生? –

+2

@LoganBesecker'$ index'沒有定義,所以你的查詢是無效的:'SELECT ... WHERE id ='。 – Wiseguy

+0

哦,jeeze,這是一個輕微的疏忽哈哈。謝謝。這解決了我最後的問題。非常感謝你 –