0

您好我尝试创建一个函数来生成选择函数。

但是下面的代码

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 子句之后的值,然后返回并显示键 => 值。

有任何想法吗?

4

1 回答 1

1

您在循环中重用$paWhere,以便附加到当前值。您需要使用一个新的数组:

$result = array();
foreach($paWhere as $lsKey => $lsValue) {
    $result[] = $lsKey . " = '" . mysql_real_escape_string($lsValue) . "'";
}
$lsQuery .= implode(" AND ", $result);
于 2009-04-01T14:05:51.283 回答