Wednesday, 18 September 2013

using Prepared statements and dynamic param

using Prepared statements and dynamic param

I'm using a prepared statement and these functions are part of a mysqli
class .They work well for singl condition But do not right answer for
multiple condition like this:
SelectByOrderCondi('user','username=? AND name=? AND email=? ' , $Array )
Here's my functions :
public function SelectByOrderCondi($Table_Name, $Conditions=''
,$Array_Conditions_Limit=null, $OrderBy='', $Limit='',
$Selected_Fields='*')
{
$Query = "SELECT ".$Selected_Fields." FROM ".$Table_Name;
if(!empty($Conditions))
$Query .= " WHERE ".$Conditions;
if(!empty($OrderBy))
$Query .= " ORDER BY ".$OrderBy;
if(!empty($Limit))
$Query .= " LIMIT ".$Limit;
$Statment = $this->ConnectionResult->prepare($Query);
if(isset($Array_Conditions_Limit) )
{
$Statment = $this->DynamicBindVariables($Statment,
$Array_Conditions_Limit);
$Statment->execute();
return $Statment->get_result();
}
else
return false ;
}
This function product dynamic bind variables
private function DynamicBindVariables($Statment, $Params)
{
if (is_array($Params) && $Params != null)
{
// Generate the Type String (eg: 'issisd')
$Types = '';
foreach($Params as $Param)
{
if(is_int($Param)) //Int
$Types .= 'i';
elseif (is_float($Param)) // Double
$Types .= 'd';
elseif (is_string($Param)) // String
$Types .= 's';
else // Blob and Unknown
$Types .= 'b';
}
// Add the Type String as the first Parameter
$Bind_names[] = $Types;
// Loop thru the given Parameters
for ($i=0; $i<count($Params);$i++)
{
$Bind_name = 'bind' . $i;
// Add the Parameter to the variable
$$Bind_name = $Params[$i];
// Associate the Variable as an Element in the Array
$Bind_names[] = &$$Bind_name;
}
// Call the Function bind_param with dynamic Parameters
call_user_func_array(array($Statment,'bind_param'), $Bind_names);
}
else
{
$Types = '';
if(is_int($Params)) //Int
$Types .= 'i';
elseif (is_float($Params)) // Double
$Types .= 'd';
elseif (is_string($Params)) // String
$Types .= 's';
else // Blob and Unknown
$Types .= 'b';
$Statment->bind_param($Types ,$Params);
}
return $Statment;
}

No comments:

Post a Comment