I'm trying to update my database with the following:
$fields = array(
'titulo',
'tipo_produto',
'quantidade_peso',
'unidade_de_venda',
'unidades_por_caixa',
'caixas_piso',
'pisos_palete',
'tipo_palete',
'unidades_palete',
'caixas_palete',
'uni_diametro',
'uni_largura',
'uni_profundidade',
'uni_altura',
'caixa_largura',
'caixa_profundidade',
'caixa_altura',
'altura_palete',
'volume_unidade',
'volume_caixa',
'volume_palete',
'peso_caixa',
'peso_palete'
);
$sql = 'UPDATE ficha_item SET '.implode(', ', array_map(create_function('$value', 'return "$value=\"" . $_POST["$value"] ."\"";'), $fields)).' WHERE id=?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_POST['item_id']));
$stmt->closeCursor();
This seems to work pretty well, but I'm wondering about the security, is this sanitized at all?
I came up with this solution after attempting (with no success) another solution:
$fields = array(
'titulo',
'tipo_produto',
'quantidade_peso',
'unidade_de_venda',
'unidades_por_caixa',
'caixas_piso',
'pisos_palete',
'tipo_palete',
'unidades_palete',
'caixas_palete',
'uni_diametro',
'uni_largura',
'uni_profundidade',
'uni_altura',
'caixa_largura',
'caixa_profundidade',
'caixa_altura',
'altura_palete',
'volume_unidade',
'volume_caixa',
'volume_palete',
'peso_caixa',
'peso_palete'
);
$sql = 'UPDATE ficha_item SET ? WHERE id=?';
$valuesClause = implode(', ', array_map(create_function('$value', 'return "$value=\"" . $_POST["$value"] ."\"";'), $fields));
$stmt = $db->prepare($sql);
$stmt->execute(array($valuesClause, $_POST['item_id']));
$stmt->closeCursor();
No errors at all, but my database would not be updated. Is my first solution sanitized at all? What went wrong with my original idea? I'm thinking it has something to do with how PDO sanitizes the query on the execute... but I'm out of ideas on where to go with it.
NOTE: The database column names and the input names are the same, that is why $value
works. In case you're also wondering, anonymous functions are out of question due to live PHP version.