Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape things within zend literal?

I'm creating an advanced search and wanted to loop through my queries by adding them to an array like so:

private $searchFields = [
    'as_first_name'                  => 'users.first_name like "%VALUE%"',
    'as_last_name'                   => 'users.last_name like "%VALUE%"',
    'as_payment_history_invoice_num' => 'users.user_id = (SELECT user_id from payment_history where payment_history.invoice_number = "VALUE" LIMIT 1)',
    'as_building_num'                => 'property_units.building_number like "%VALUE%"',
    'as_residents_email'             => 'users.email like "%VALUE%"',
    'as_property_name'               => 'property.name like "%VALUE%"',
    'as_phone_num'                   => 'REPLACE(REPLACE(REPLACE(REPLACE(users.phone, " ", ""), "(", ""), ")", ""), "-", "") = "VALUE"',
    'as_unit_num'                    => 'property_units.unit_number = "VALUE"',
    'as_account_status'              => 'user_status.status_name = "VALUE"'
];

so on search I'm doing something like..

if (array_key_exists($key, $this->searchFields)) {

    $form->get($key)->setValue($val);
    $where->NEST->literal(str_replace('VALUE', urldecode($val), $this->searchFields[$key]))->UNNEST;
}

but the issue is I'm not escaping anything there. Not good. How can I use the same structure but also be escaping stuff.

like image 739
hamobi Avatar asked Feb 13 '17 17:02

hamobi


1 Answers

Literal predicate is for the cases when there are no placeholders. You should use Expression predicate instead.

private $searchFields = [
    'as_first_name'                  => 'users.first_name like "?"',
    'as_last_name'                   => 'users.last_name like "?"',
    'as_payment_history_invoice_num' => 'users.user_id = (SELECT user_id from payment_history where payment_history.invoice_number = "?" LIMIT 1)',
    'as_building_num'                => 'property_units.building_number like "?"',
    'as_residents_email'             => 'users.email like "?"',
    'as_property_name'               => 'property.name like "?"',
    'as_phone_num'                   => 'REPLACE(REPLACE(REPLACE(REPLACE(users.phone, " ", ""), "(", ""), ")", ""), "-", "") = "?"',
    'as_unit_num'                    => 'property_units.unit_number = "?"',
    'as_account_status'              => 'user_status.status_name = "?"'
];

zend-form values should already be decoded, so urldecode is not needed

if (array_key_exists($key, $this->searchFields)) {

    $form->get($key)->setValue($val);
    $where->NEST->expression($this->searchFields[$key], $val)->UNNEST;
}

I didn't use zend-db in quite a while, make sure to check that this code is actually producing the query you need.

like image 140
Xerkus Avatar answered Nov 11 '22 17:11

Xerkus