BobbyP
BobbyP

Reputation: 2245

mysqli's bind_param using an array

I am trying to insert values into a database using mysqli prepared statements. The values that will be inserted will vary at runtime, so I am trying to use variables instead of listing out all the parameters. I have seen that I can use call_user_func_array to achieve this, but this doesn't seem to work.

My code so far is below, albeit greatly reduced and modified for simplicity:

// in the real world, these will be set dynamically
$table = 'my_table';
$sql_fields = 'field_1,field_2,field_3,field_4';
$sql_types = 'ssss';
$sql_holders = '?,?,?,?';
$data = array('value_1', 'value_2', 'value_3', 'value_4');

$stmt = $con->prepare("INSERT INTO $table ($sql_fields) VALUES ($sql_holders)");
$params = array_merge(array($sql_types), $data);
call_user_func_array(array($stmt, "bind_param"), $params);

If I var_dump $params, I get the following.

array(5) {
    [0]=>
    string(4) "ssss"
    [1]=>
    string(7) "value_1"
    [2]=>
    string(7) "value_2"
    [3]=>
    string(7) "value_3"
    [4]=>
    string(7) "value_4"
}

This all seems okay to me, yet when I run the script, PHP crashes. I can comment out the "call_user_func_array" line and it works. Obviously nothing happens, but it doesn't crash.

I am afraid I don't know too much about my environment, except that I am using PHP 7, PhpStorm IDE and WAMP. When PHP crashes, I get the PhpStorm error "CLI has stopped working". My research tells me that this error is a PHP crashing and not the IDE, so the problem should be with my code. (incidentally, I have tried this on two machines running PhpStorm and get the same result, so this research seems to be validated)

Is anyone able to shed some light on this?

Thanks

Upvotes: 2

Views: 1318

Answers (1)

Ivan
Ivan

Reputation: 81

Can you try this, to send reference to values instead of real values:

    $params = array_merge(array($sql_types), $data);
    foreach( $params as $key => $value ) {
        $params[$key] = &$params[$key];
    }
    call_user_func_array(array($stmt, "bind_param"), $params);

Upvotes: 3

Related Questions