0

I have an html form in which I want to use the inputs in a SQL query. Instead of the first php code, I want to use the alternative php code below, but I receive php parse error for the line including ${$key} = $value in alternative php code. maybe this syntax has been removed in newer versions of php. I appreciate if anyone could help me correct the syntax or suggest a different code to do me the same thing. Thanks in advance.

The error I receive: Parse error: "syntax error, unexpected '$', expecting case (T_CASE) or default (T_DEFAULT) or '}' "

html code:

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<select name="my_input1">
<option value="val1">a</option>
<option value="val2">b</option>
<option value="val3">c</option>
</select>
<select name="my_input2">
<option value="val4">d</option>
<option value="val5">e</option>
</select>
</form>

main php code:

$inputs = array();
$queries = array();
foreach($inputs as $key => $value){
    array_push($queries,"table_name.column1 = $_POST['my_input1']");
    array_push($queries,"table_name.column2 = $_POST['my_input2']");
} 

Alternative php code:

$inputs = array();
$queries = array();
foreach($inputs as $key => $value){
    ${$key} = $value; 
    array_push($queries,"table_name.column1 = $my_input1");
    array_push($queries,"table_name.column2 = $my_input2");
}
4lisalehi
  • 29
  • 3
  • 14
  • 1
    I don't see the point of having this: `${$key} = $value;`, also note that you are using foreach on an empty array from what your question shows. – Ende Neu Aug 10 '14 at 12:46
  • Please post the exact error message you are receiving. Your "main" code would generate [`unexpected T_ENCAPSED AND WHITESPACE`](http://stackoverflow.com/a/13935532/541091) -- the alternative code would be syntactically valid, but I can't tell what you are trying to accomplish other than to load local variables from `$key`. – Michael Berkowski Aug 10 '14 at 12:47
  • Once you get the syntax correct, using the array in the "main" version is probably preferred - variable variables have a bad effect on readability and pollute your code with lots of unnecessary extra variables. – Michael Berkowski Aug 10 '14 at 12:49
  • All that said, it looks like you are trying to construct a SQL statement with these. Having no escaping on the input, this query will be vulnerable to SQL injection. – Michael Berkowski Aug 10 '14 at 12:49
  • Added the exact error message. – 4lisalehi Aug 10 '14 at 12:58
  • Could you add also some motivation to what you are trying to achieve? – Ende Neu Aug 10 '14 at 12:59
  • Are you trying to "auto-create" `$my_input1` and `$my_input2` with `${$key}`? What for? Just use `$value` directly. You're also not going to get both at the same iteration (you would have to setup the for loop quite a bit differently, as well as the var create lines). – Jared Farrish Aug 10 '14 at 13:14

0 Answers0