2017-06-21 44 views
-2

我試圖寫一個事先準備好的聲明的功能,但是當我運行的代碼,它給我一個錯誤:預處理語句函數 - 範圍錯誤

mysqli_stmt_store_result() expects parameter 1 to be mysqli_stmt, null given 

我的功能如下所示:

function fn_preparedStatement($query, $types, $values){ 
    global $dbconnection; 
    if (!$dbconnection) { 
     die("Function wm_dynamicForm connection failed.</br>"); 
    } 
    $db = mysqli_stmt_init($dbconnection); 
    if (mysqli_stmt_prepare($db, $query)) { 
     mysqli_stmt_bind_param($db, $types, ...$values); 
     if (!mysqli_stmt_execute($db)) { 
      echo "Execute Error: " . mysqli_error($dbconnection); 
     } 
    } else { 
     echo "Prep Error: " . mysqli_error($dbconnection); 
    } 
} 

然後在我的代碼,我有:

$query = "SELECT * FROM Contacts WHERE First_Name = ?"; 
    $types = "s"; 
    $values = array("Mike"); 
    fn_preparedStatement($query, $types, $values); 
    mysqli_stmt_store_result($db); //im getting the error on this line - null 

所以IM思考我的問題是一個範圍的問題。我不確定要從我的功能中「返回」來完成這項工作。當我編寫內聯代碼時,它工作正常。當我將準備好的語句移動到一個函數中,並用現在正在出錯的函數替換內聯代碼時。有人可以告訴我在哪裏搞亂了嗎?非常感謝。

+0

您可能需要返回'$ db',或者我建議重新考慮你是如何建立你的數據庫的功能。 – aynber

+0

@ user982853我刪除了我的評論,我很困惑。當做這樣的事情時,'$ db'不是一個好的變量,並且應該更像'$ query'(如果有的話)。你的代碼很混亂。 –

+0

'$ db'從哪裏來。你不會從函數返回語句句柄,所以它是神奇的 – RiggsFolly

回答

0

你需要從函數返回的語句句柄

function fn_preparedStatement($query, $types, $values){ 
    global $dbconnection; 
    if (!$dbconnection) { 
     die("Function wm_dynamicForm connection failed.</br>"); 
    } 
    $db = mysqli_stmt_init($dbconnection); 
    if (mysqli_stmt_prepare($db, $query)) { 
     mysqli_stmt_bind_param($db, $types, ...$values); 
     if (!mysqli_stmt_execute($db)) { 
      echo "Execute Error: " . mysqli_error($dbconnection); 
     } 
    } else { 
     echo "Prep Error: " . mysqli_error($dbconnection); 
    } 

    // 
    return $db; 
    // 
} 

// main line code 
$query = "SELECT * FROM Contacts WHERE First_Name = ?"; 
$types = "s"; 
$values = array("Mike"); 

// accept the stantement handle from the function 
$db = fn_preparedStatement($query, $types, $values); 

// so now you can use it 
mysqli_stmt_store_result($db); //im getting the error on this line - null 
+0

工作正常!我認爲我在電腦上呆了太久。我添加返回到我的函數,但忘記將結果放入我的代碼中的var。非常感謝。有時候所需要的只是第二套眼睛。 – user982853