I have to work with the following PDO connection query:
$fields = array(
'titulo',
'tipo_produto',
'quantidade_peso',
'unidade_de_venda',
'unidades_por_caixa',
'caixas_piso',
'pisos_palete',
'tipo_de_palete',
'unidades_palete',
'caixas_palete',
'uni_diametro',
'uni_largura',
'uni_profundidade',
'uni_altura',
'uni_peso_bruto_unidade',
'caixa_largura',
'caixa_profundidade',
'caixa_altura',
'altura_palete',
'volume_unidade',
'volume_caixa',
'volume_palete',
'peso_caixa',
'peso_palete'
);
$sql = 'INSERT INTO ficha_item ( %s ) VALUES ( %s )';
$fieldsClause = implode(', ', $fields);
$valuesClause = implode(', ', array_map(function($value) {
return ':' . $value;
}, $fields));
$sql = sprintf($sql, $fieldsClause, $valuesClause);
$stmt = $db->prepare($sql);
$stmt->execute(array_intersect_key($_POST, array_flip($fields)));
This was returning me the following error:
Parse error: syntax error, unexpected T_FUNCTION, expecting ')'
After some digging around, it seems that anonymous functions were only implemented in PHP 5.3, for me to get this working on 5.2, I should use create_function, I'm still pretty new to PHP, so I'm having issues figuring out the right syntax here, I also don't really understand the $value variable and how to implement it correctly on create_function.
Looking for some help here or even alternatives to create_function.
create_functionis almost as messy asevalsince it involves putting code in a string. Yuck!create_function('$value', 'return ":".$value;')- you literally put the argument list as a string in the first argument, and the function body code in the second. The only thing to be aware of is the quote types you use and how they will come out of the other end - you shouldechothe string you pass and make sure it is valid PHP code you are not sure. Although it's also often better to create a named function and just pass the function name as a string, it's usually more readable. The best solution though, as mentioned above, is to update your PHP version.