mysqli的bind_param使用数组 [英] mysqli's bind_param using an array

查看:49
本文介绍了mysqli的bind_param使用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mysqli准备好的语句将值插入数据库.将插入的值在运行时会有所不同,因此我尝试使用变量而不是列出所有参数.我已经看到可以使用call_user_func_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);

如果我var_dump $ 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"
}

这一切对我来说似乎还可以,但是当我运行脚本时,PHP崩溃了.我可以注释掉"call_user_func_array"行,并且它可以工作.显然没有任何反应,但是不会崩溃.

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.

除非我使用的是PHP 7,PhpStorm IDE和WAMP,否则我对我的环境不了解太多. PHP崩溃时,出现PhpStorm错误"CLI停止工作".我的研究告诉我,此错误是PHP崩溃而不是IDE崩溃,所以问题应该出在我的代码上. (顺便说一下,我已经在运行PhpStorm的两台计算机上进行了尝试,并获得了相同的结果,因此这项研究似乎得到了验证)

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?

谢谢

推荐答案

可以尝试发送对值而不是实际值的引用:

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);

这篇关于mysqli的bind_param使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆