I’m extending a cakePHP 1.3.13 site and my user needs to be able to practically generate their own SELECT queries on some data via a web app. They were literally querying an MS Access database before but they will now have to use form controls to search via the site, but they are used to and require a degree of flexibility.
They’re searching through tickets and there are a couple of SELECT fields they don’t always need to see and a couple of WHERE conditions they don’t always need to filter by, and I’m trying to find out how to allow the functionality without adding the security wholes of dynamic SQL.
Here’s my find method:
$tickets = $this->Hauler->find('all', array(
'conditions'=>array("ticketDate between'$startDate' and '$endDate'", "LocationID='$plant_id'", 'paid=0'),
'fields'=>array('LocationID','OrderID','TicketDate','TicketNo','FreightPay','Qty','Total', 'Paid'),
'order'=>array('TicketDate', 'LocationID','OrderID'),
));
The only ways I can think to include dynamic fields would either be use if statements to select one of a predefined set of all possible combinations of fields (not scalable, annoying) or to create a $fields array to append to the [fields] key.
The conditions have similar issues and I’m already uncomfortable including string concatenation like between '$startDate' but I don’t know of a better method there. CakePHP claims they sanitize for me if I use the find() method but I’m not sure how well.
Is there a specific method to allow these “dynamic” searches without risky actually dynamic SQL? I would like to continue to use CakePHP’s ‘find()’ method, I know Stored Procedures allow me to do just this, but this is a case where I want the logic in the code. Also, should I take additional sanitization steps beyond what Cake’s find() method does in any case?
I only have two very trusted users so security isn’t the biggest concern in this exact search, but I’d really like to know how to do this sort of find properly.
Update: I’ve updated my code and solved the fields problem as per @Anh Pham’s suggestion, but I still can’t get optional conditions working yet. Here’s my new code:
$tickets = $this->Hauler->find('all', array(
'conditions'=>array('Hauler.ticketDate BETWEEN ? AND ?' => array($startDate,$endDate), 'Hauler.LocationID'=>$plant_id, 'Hauler.paid'=>0),
'order'=>array('TicketDate', 'LocationID','OrderID'),
));
This generates queries like WHERE LocationID='' if LocationID is not submitted via the form, instead of checking for an empty string I would like my query to omit the LocationID= portion of the WHERE clause if no LocationID is provided.
First:
Users can only see fields that you output, not all fields in the results.
create a $fields array to append to the [fields] key, which is obviously unsafe.I don’t see how it’s unsafe.Cake’s find() shields you from SQL injection. So I don’t really see a security issue here.