bcosca / fatfree

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!
2.66k stars 446 forks source link

Sql Mapper: Misleading error message when setting value for non existent field in the mapped table #1266

Closed paolobertani closed 1 year ago

paolobertani commented 1 year ago

Given this code

$mapper->reset();
$mapper->set( 'foo', 'bar' ); // <--- Error here: `foo` does not exists in the table
$mapper->insert();

Where foo is a column that does not esist in the mapped table I get this error

Internal Server Error

SQLSTATE[42S22]: Column not found:
1054 Unknown column 'bar' in 'field list' 
[/var/www/example.com/html/lib/php/fatfreeframework/DB/SQL.php:230]

The error message is misleading in fact the non existent column is foo, not bar: the latter is the value that has been attempted to set to the non-existent column.

Why does this happen? Is there a way to fix this?

ikkez commented 1 year ago

This is currently the expected behavior because setting a field not existing = defining an adhoc field.

$mapper->set('count_x', 'SELECT COUNT(id) from x where x.id = y.foreign_key group by x.id');

ref.: https://fatfreeframework.com/3.8/databases#VirtualFields

ikkez commented 1 year ago

The way to fix this is to apply a whitelist of fillable fields that are allowed to be set in case you are using something like copyfrom.

i.e.:

$mapper->copyfrom('POST', function($val) {
    return array_intersect_key($val, array_flip(['first_name', 'last_name', 'age']));
});
paolobertani commented 1 year ago

ok, I got it

thank you