0

我在网上看到了这个功能,为MySQli带来了对命名参数的基本支持:

function parseNamedParams(&$queryStr, &$params)
{
    $array = array();
    if ($c = preg_match_all('/(:\w+)/is', $queryStr, $matches)) { // To match words starting with colon
        $list = $matches[0]; // $matches is two-dimensional array, we only need first element
        foreach($list as $value) { // We'll replace each parameter in the query string with a '?' (as to comply with mysqli), and make sure the value is in the correct order.
            $queryStr = str_replace($value, '?', $queryStr);
            $array[] = $params[$value];
        }
        $params = $array;
    }
}

我一直在尝试使用它:

$DB = new mysqli("host","user","pass","db");
$Query = "SELECT uname FROM test WHERE uname = :user";
$Params = array (
":user" => "Sophie"
);
$Bind = parseNamedParams($Query, $Params);

$SQL = $DB->prepare($Bind);
$SQL->execute();
$SQL->bind_result($Username);
$SQL->fetch();
$SQL->close();

但是,唉,这行不通

更新 忘记包含错误消息:

致命错误:在第 25 行对 C:\xampp\htdocs\index.php 中的非对象调用成员函数 execute()

4

1 回答 1

-1

如果您正在寻找 PDO Style 准备好的语句,然后切换到 PDO ......但是如果您真的坚持这样做,那么我有以下解决方案:

function Named_Params ($Query, $Params,$DBLink){
    $New_Param = array_values($Params);
    $Count = 0;
    if (preg_match_all('/(:\w+)/is',$Query,$Match)){
        $List = $Match[0];
        foreach ($List AS $Value){
            $Secure_Var = $DBLink->real_escape_string($New_Param[$Count]);
           $Query = str_replace($Value,$Secure_Var, $Query);
            $Count++;
        }
    }
    return $Query;
}
$DB = new mysqli("","","","");
$Query = "SELECT uname FROM test WHERE uname = ':user'";
$Params = array (
    ":user" => "Sophie"
);
$Input = Named_Params($Query,$Params,$DB);

$Query = $DB->prepare($Input);
$Query->execute();
$Query->bind_result($Username);
$Query->fetch();
$Query->close();
    echo $Name;

希望这就是你要找的

于 2013-10-11T20:56:44.803 回答