Search code examples
phpmysqliprepared-statement

is there a way to get bind_param to accept a variable number of arguments


i'm trying to make a mysql query wrapper function for PHP, now currently i'm trying to use prepared statements since they are apparently the best way to do MySQL queries in SQL, so far this is what i have

public function run_query($query)
{
    $arguments = $query['arguments'];
    $prep = $this->connection->prepare($query['query'])
    $dtString = '';

    foreach($arguments as $_field => $_argument)
    {
        $dtString .= array_keys($_argument);
    }
}

the structure of $query is like this

$query =    array( "query" => QUERY,
                  "arguments" => array(FIELD => array(DATATYPE => VALUE)))

and example of what $query could be is this

$query =    array( "query" => "SELECT * FROM table_1 WHERE active = ? AND group = ?",
                  "arguments" => array("active" => array("i" => 1),
                                       "group" => array("i" => 17)))

now as you can see, what i'm trying to do is to make my function allow any query in regardless of what the query is and how many arguments you want to use.

now in my function, the next step after the for each is to use $prep->bind_param($dtString, [VALUES]); however i read that each value is a separate argument in the function which kinda messes things up

i'm wondering if there is a way to get bind_param in my function to accept a variable number of arguments

my current solution is to create another function, pass $arguments in as an argument to the function, move my for each into the new function and after creating $dtString counting it size and having a switch case which just has multiple bind_param but with different numbers of arguments like this

switch($count)
{
    case 1:
        $prep->bind_param($dtString, $array[0]);
        break;
    case 2:
        $prep->bind_param($dtString, $array[0], $array[1]);
        break;
    case 3:
        $prep->bind_param($dtString, $array[0], $array[1], $array[2]);
        break;
}

but i rather avoid having to code something like this


Solution

  • If you want to stick with native prepared statements only, PDO is the only [sane] choice
    Dunno what your function intended to return but assuming all the data from the query:

    public function run_query($query, $params)
    {
        $stm = $this->connection->prepare($query)
        $stm->execute($params);
        return $stm->fetchAll();
    }
    
    $query = "SELECT * FROM table_1 WHERE active = ? AND group = ?";
    $data  =  $db->run_query($query, array(1, 17));