准备语句功能 - 范围错误

时间:2017-06-21 18:35:05

标签: php mysql function prepared-statement

我正在尝试为预备语句编写函数,但是当我运行代码时,它给了我一个错误:

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替换内联代码时,现在得到错误。有人可以告诉我哪里搞砸了吗?非常感谢你。

1 个答案:

答案 0 :(得分: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