views:

231

answers:

2

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 protected] AND 2d1cf648ca2f0b2499e62ad7386eccc2 AND 1 AND per_email = '[email protected]' 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?

+1  A: 

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);
Konrad Rudolph
A: 

Thanks,

One other short question about the use of try /catch methods.

If you look at my first post. Is this the correct way of using try catch blocks?

Because this function throws an exception and can catch its own exception?!

sanders