Bind multiple parameters into mysqli query

2018-12-31 09:22发布

Right now I am having to use the following structure to cope with binding multiple parameters into a mysqli query:

if ($words_total == 1)
{
    $statement -> bind_param("s", $words[0]);
}
else if ($words_total == 2)
{
    $statement -> bind_param("ss", $words[0], $words[1]);
}
else if ($words_total == 3)
{
    $statement -> bind_param("sss", $words[0], $words[1], $words[2]);
}

//and so on....

I work out the number of question marks using the code below and insert it into my query:

$marks = "";
for($i = 1; $i<=$words_total; $i++) {
    if ($i == $words_total)
    {
        $marks .= "?";
    }
    else
    {
        $marks .= "?,";
    }
}

My question is surely there must be a way of handling as many inputs into the query as I need dynamically. Hardcoding the bind_param() seems like a really bad way of handling this.

I am using php version 5.4.10

1条回答
琉璃瓶的回忆
2楼-- · 2018-12-31 09:34

Here goes the solution or the actual problem of binding a variable number of values to mysqli prepared statement:

<?php
$values = array('b','c','d');

$in  = str_repeat("?,", count($values));
$in  = trim($in, ",");

$sql = "SELECT * from users where username in($in)";
$stm = $con->prepare($sql);

$types = str_repeat("s", count($values));

if (strnatcmp(phpversion(),'5.3') >= 0)
{
    $bind = array();
    foreach($values as $key => $val)
    {
        $bind[$key] = &$values[$key];
    }

} else {

    $bind = $values;
}

array_unshift($bind, $types);
call_user_func_array(array($stm, 'bind_param'), $bind);

#var_dump($sql, $types, $bind, $con->error);

$stm->execute();
$res = $stm->get_result();
while($row = $res->fetch_assoc()) var_dump($row);

Commented line is for development testing only. Extremely useful.

But your initial problem was lack of error reporting.

It spoiled you not only in this particular case but your whole experience with PHP.
Every time when something goes wrong, PHP will tell you - what happened and whom to blame. Only if you let it. And you always should.

You may read this answer on error reporting basics

While having an error message, you can simply google for it and find a solution in seconds. Or at least you will know, what certain problem you have. Which is actually behavior of call_user_func_array() function, that was suddenly changed.

查看更多
登录 后发表回答