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.)
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.
Is this what you want? Creates variables called $column1 , 2 etc. From string.
$string = "column1, column2, boo3";
$arr = explode(", ", $string);
Foreach($arr as $var){
$$var = $var;
}
Echo $column1 . $column2 . $boo3;
https://3v4l.org/sW0cu
Double $
will grab the variables value and use that as name for the variable.