我在网上看过这个功能,为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();
但是,这不起作用
更新 忘记包含错误消息:
致命错误:在非对象中调用成员函数execute() 第25行的C:\ xampp \ htdocs \ index.php
答案 0 :(得分:-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;
希望这就是你要找的东西