So I'm trying to create a function that generates a SQL query string based on a multi dimensional array.
Example:
function createQueryString($arrayToSelect, $table, $conditionalArray) {
$queryStr = "SELECT ".implode(", ", $arrayToSelect)." FROM ".$table." WHERE ";
$queryStr = $queryStr.implode(" AND ",$conditionalArray); /*NEED HELP HERE*/
return $queryStr;
}
$columnsToSelect = array('ID','username');
$table = 'table';
$conditions = array('lastname'=>'doe','zipcode'=>'12345');
echo createQueryString($columnsToSelect, $table, $conditions); /*will result in incorrect SQL syntax*/
as you can see I need help with the 3rd line as it's currently printing
SELECT ID, username FROM table WHERE lastname AND zipcode
but it should be printing
SELECT ID, username FROM table WHERE lastname = 'doe' AND zipcode = '12345'
I know this is for the case of a pdo mysql type.. but what i do is build pdo wrapper methods, and in this case i do this function that helps to build the string, since we work with keys, there is no possible way to mysql inject, since i know the keys i define / accept manually.
imagine this data:
you defined utils methods...
then the query bind array builder ( i could use direct array reference but lets simplify):
then you execute...
You could also go for an update easy with...
Here is a working version:
Untested, but something like this should work. This way you can also check if $item is an array and use IN for those cases.
You will have to write another function to process the
$conditionalArray
, i.e. processing the$key => $value
and handling the types, e.g. applying quotes if they're string.Are you just dealing with
=
condition? What aboutLIKE
,<
,>
?I use a variation of this:
It's rough but works.
Try this