I am using Zend's insert()
function to insert records in a database table.
Eg.
From the database model object, I am calling Zend_Db_Table's insert()
function and passing the incoming data as an array - $data
, ie
$this->insert($data);
$data
is an array. The contents of $data
are of mixed datatypes -integer, money, text etc.
In order to validate the incoming $data
array, I wrote a function, verifyData($data)
.
private function verifyData(&$data) {
//Trim whitespace characters from incoming data.
foreach($data as $key => $val)
{
$data[$key] = trim($val);
if(empty($data[$key])) {
unset($data[$key]);
}
}
//Checking for not null table columns
if( empty($data['id']) || empty($data['name']) || empty($data['age'])) {
error_log("One of the required fields is missing");
return false;
}
else {
return true;
}
}
As written above,this function :
- trims the incoming data and unsets any fields from the $data array, if they are empty.
- Then this function checks for the presence of required fields and if any required field is missing, it returns false. In this particular definition, id, name and age are required. However, there could be other non required fields as well that I want to validate. Eg $data['salary']
I need help/suggestions in adding following validations to the above function / in any other way possible:
- I want to check if the datatype of each element of the array is as expected/ convert it to a particular datatype before I insert the data.
- I want to convert/process the incoming data such that any threat of SQL injection is taken care of.
One way to take care of the datatype check is that I loop through the incoming data array and convert specific column values to their datatypes and validate. But I want to find out if there is any efficient/standard way to implement the above two points.
An example scenario is, eg on my webform, when the new person is added to db, I need to enter name, age and salary out of which name and age are compulsory. Age and salary should be entered as integers only. I want to implement this restriction on the php level and I am using Zend Framework.
Any help/suggestions would be really appreciated.