2017-06-21 91 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