Question

Hello I try to create a function to generate select functions.

But the following code

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;
}

generates this sql statement:

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'

I don't know why it first shows only the values after the where clause and then goes back and shows the key => values.

Any idea's?

Was it helpful?

Solution

You reuse $paWhere in your loop so you append to the current values. You need to use a fresh array:

$result = array();
foreach($paWhere as $lsKey => $lsValue) {
    $result[] = $lsKey . " = '" . mysql_real_escape_string($lsValue) . "'";
}
$lsQuery .= implode(" AND ", $result);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top