【问题标题】:php select function generates weird where clausephp select函数生成奇怪的where子句
【发布时间】:2009-04-01 22:40:59
【问题描述】:

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

但是下面的代码

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 => 值。

有什么想法吗?

【问题讨论】:

    标签: php select associative-array


    【解决方案1】:

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

    $result = array();
    foreach($paWhere as $lsKey => $lsValue) {
        $result[] = $lsKey . " = '" . mysql_real_escape_string($lsValue) . "'";
    }
    $lsQuery .= implode(" AND ", $result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-09
      • 2016-03-19
      • 2017-03-29
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多