doukuang8166 2017-07-22 14:59
浏览 215
已采纳

动态生成要在PHP预准备语句的bind_param()函数中使用的变量名

I was wondering if it's possible to store the variables to be inserted in a bind_param() function inside another variable such that if this were the original query:

$stmt->bind_param("si", $column1, $column2);

would it be possible to store the 2 variables inside another variable, i.e:

$columns = $column1.','.$column2;

And then if the new variable can be used inside the bind_param() function like this such that it works:

$stmt->bind_param("si", $columns);

My Database column names and php variable names are the same (except for the '$' sign of course), so I tried this:

$string = "column1, column2";

function convert_to_variables($string) {

        // Convert column names to an array
        $array = explode(", ", $string); 

        // Convert column names array values to a variable
        foreach ($array as $key => $value) {
            $array_values_with_dollar[] = $$value; // (previously tried with '$'.$value)
        }

        // Convert to string again
        $imploded = implode(", ", $array_values_with_dollar); 

        return $imploded;
}

.
.
$variables = convert_to_variables($string);
.
.
$stmt->bind_param("si", $variables );
.
.
// Everything else like $stmt = $dbc->prepare(""); and $stmt->execute(); etc exists. 
// The bind_param() is the only line with an error.

(Right now I'm getting an 'Undefined variable: column1' error.)

  • 写回答

2条回答 默认 最新

  • duandange7480 2017-07-22 15:07
    关注

    It's not possible to do with strings directly, because it'd be interpreted as just that - a single string, and not a combination of strings that'd make up the values for each column. Using that logic, you'd also have issues if one of your strings actually contains ', 'as well - then it wouldn't match up with number of values and number of parameters.

    I can suggest an alternative using arrays instead. You can use that string as a base if you really need to, and use explode() on that. In any case, using an array, you can use the "unpacking operator" ... to unpack the array.

    $string = "column1, column2";
    $boom = explode(", ", $string);
    $stmt->bind_param("ss", ...$boom);
    

    Alternatively build it as an array, and use that (which effectively is the same). This approach is better, as it will not produce more values than parameters if one or more of the strings contains a comma ,.

    $variables = array("column1", "column2");
    $stmt->bind_param("ss", ...$variables);
    

    Also note that I've changed "types" parameter to ss (was si), because both your parameters are in fact strings.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?