How to dynamically bind params in mysqli prepared statement?

前端 未结 1 1863
天涯浪人
天涯浪人 2021-01-06 12:11

I\'m trying to create a function for my project. I would like it to handle all the check functions. What I mean with that is before you start inserting a row in your databas

1条回答
  •  别那么骄傲
    2021-01-06 12:47

    You are on a very right track! Such a function should be an everyday companion for the every PHP programmer using mysqli, but strangely, only few ever have an idea of creating one.

    I've had an exactly the same idea once and implemented a mysqli helper function of my own:

    function prepared_query($mysqli, $sql, $params, $types = "")
    {
        $types = $types ?: str_repeat("s", count($params));
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        return $stmt;
    }
    

    Main differences from your approach

    • the connection is made only once. Your code connects every time it executes a query and this is absolutely NOT what it should do
    • it can be used for any query, not only SELECT. You can check the versatility of the function in the examples section down in the article
    • types made optional as most of time you don't care for the type
    • no bizarre $location variable. Honestly, whatever HTTP stuff should never be a part of a database operation! If you're curious how to properly deal with errors, here is my other article Error reporting in PHP

    With your example query it could be used like this

    $check = prepared_query($sql, [$id, $mail])->get_result()->fetch_row();
    

    or, if you want a distinct function, you can make it as well

    function check_database($mysqli, $sql, $params, $types = "")
    {
        return prepared_query($mysqli, $sql, $params, $types)->get_result()->fetch_row();
    }
    

    and now it can be called as

    $check = check_database($sql, [$id, $mail]);
    

    0 讨论(0)
提交回复
热议问题