在 Mysqli 中使用预准备语句和动态参数


using prepared statements and dynamic param in mysqli

我正在使用预准备语句,这些函数是mysqli类的一部分。它们适用于单点条件,但对于这样的多个条件不要正确回答:

SelectByOrderCondi('user','username=? AND name=? AND email=? ' , $Array )

这是我的函数:

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 ;
}

添加我的类此函数:

Private function GetType($Item)
{
    switch (gettype($Item)) {
        case 'NULL':
        case 'string':
            return 's';
            break;
        case 'integer':
            return 'i';
            break;
        case 'blob':
            return 'b';
            break;
        case 'double':
            return 'd';
            break;
    }
    return '';
}

并更改动态绑定变量函数,如下所示:

public function DynamicBindVariables($Statment, $Params)
{
    if (is_array($Params) && $Params != null)
    {
        // Generate the Type String (eg: 'issisd')
        $Types = '';
        foreach($Params as $Param)
        {
            $Types .= $this->GetType($Param);
        }
        // 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 .= $this->GetType($Param);
        $Statment->bind_param($Types ,$Params);
    }
    return $Statment;
}

现在它工作正常

请注意,您的代码在确定类型时可能不正确,请参阅此测试:

var_dump(is_int("1"));      //bool(false)
var_dump(is_float("1.1"));  //bool(false)
var_dump(is_string("1.1")); //bool(true)

您可以使用:

整数或if((int) $Param == $Param)ctype_digit()

is_numeric()用于浮子或if((float)$Param == $Param)