Mysqli bind with an array of values

Asked

Viewed 245 times

7

I have a PDO code and I need to convert this code to mysqli, right now I have something like:

$sql = "SELECT * from tabela where nome = ? AND idade = ? AND outro = ?";

$stmt = $core->conn->prepare($sql);

$bindArray = array( $_POST['nome'], $_POST['idade'], $_POST['outro'] );

$stmt->execute($bindArray);

The problem is in $bindArray, in PDO in function run the $bindArray variable and it automatically binds to the array, in mysqli I’m not able.

What may or may not be possible to do the same with mysqli?

  • I am aware of these solutions, but I want to know if it is possible to bind as in PDO, without resorting to the use call_user_func_array and the like.

  • 1

    Today not possible, Mysqli sins in some things and is also good in others.

  • 1

    I don’t know, but right now what I’m saying is that you’d have to come up with a very complex expression to do that job. Maybe not very complex, but it wouldn’t be simple either. If I have more time available, we’ll see.

  • 1

    @Edilson, Since the API does not provide anything that does this, I would very much like to see your solution without using call_user_func_array(). There are technical reasons for execute() not receiving an array and bind_param() only accept references.

  • 2

    Actually it does, but I didn’t say the solution wouldn’t be based on function call_user_func_array. Perhaps I misread your comment, but there is still an alternative, laborious and not recommendable form.

Show 1 more comment

1 answer

2


Currently cannot pass an array to execute() of Mysqli in the same way that execute() of PDO, pass values also directly via bind_param() it is not possible, curiously function returns generate a Warning and work.

The solution for versions prior to PHP5.6 is to use call_user_func_array() how the answers in the links show.

How do I pass dynamic parameters in a preparedStatment? and Select in Mysql with an array

Select in Mysql with an array

Approach with PHP5.6

With PHP 5.6 and help from ...(unpacking Arguments) it is possible to pass an array to bind_param() simply.

$valores = array('Doge', '[email protected]', 'wow value');
$stmt = $mysqli->prepare('INSERT INTO t (c1,c2,c3) VALUES(?,?,?)');
$stmt->bind_param('sss', ...$valores);
if(!$stmt->execute()){
     echo $stmt->error;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.