您好我尝试创建一个函数来生成选择函数。
但是以下代码
public function select($psTableName, $paFields ="",$paWhere=array())
{
//initial return value
$lbReturn = false;
try
{
$lsQuery = "SELECT * FROM `";
$lsQuery .= $psTableName;
$lsQuery .= "` ";
if (!empty($paWhere)){
$lsQuery .= "WHERE ";
print_r($paWhere);
foreach($paWhere as $lsKey => $lsValue)
{
echo $lsKey."<br>";
$paWhere[] = $lsKey." = '".mysql_real_escape_string($lsValue)."'";
}
$lsQuery .= implode(" AND ", $paWhere);
//$lsQuery = substr($lsQuery,0,(strlen($lsQuery)-5));
}
//echo $lsQuery;
//execute $lsQuery
$this->msLastQuery = $lsQuery;
if(!$this->execute())
{
throw new DBException("Select failed, unable to execute query: ".$lsQuery);
}
else
{
$lbReturn = true;
}
}
catch(DBException $errorMsg)
{
ErrorHandler::handleException($errorMsg);
}
return $lbReturn;
}
生成这个sql语句:
SELECT * FROM `persons` WHERE email@gmail.com AND 2d1cf648ca2f0b2499e62ad7386eccc2 AND 1 AND per_email = 'email@gmail.com' AND per_password = '2d1cf648ca2f0b2499e62ad7386eccc2' AND per_active = '1'
我不知道为什么它首先只显示where子句后面的值,然后返回并显示key =&gt;值。
有什么想法吗?
答案 0 :(得分:1)
您在循环中重复使用$paWhere
,以便附加到当前值。你需要使用一个新的阵列:
$result = array();
foreach($paWhere as $lsKey => $lsValue) {
$result[] = $lsKey . " = '" . mysql_real_escape_string($lsValue) . "'";
}
$lsQuery .= implode(" AND ", $result);