tags:

views:

75

answers:

3

Hello,

I'm trying to create an flexible update query. I have now something like this:

      $lsQuery = "UPDATE `";
  $lsQuery .= $psTableName;
  $lsQuery .= " SET ";
  foreach($psValues as $lsKey => $lsValue)
  {
   $lsQuery .= $lsKey;
   $lsQuery .= " = '";
   $lsQuery .= $lsValue;
   $lsQuery .= "' AND ";
  }
  $lsQuery .= "` ";
  $lsQuery .= "WHERE ";
  if(isset($psWhere)){
   foreach($psWhere as $lsKey => $lsValue)
   {
    $lsQuery .= $lsKey;
    $lsQuery .= " = '";
    $lsQuery .= $lsValue;
    $lsQuery .= "' AND ";
   }
  }
  $lsQuery = substr($lsQuery,0,(strlen($lsQuery)-5));

But when I print my query on the screen I get something like:

UPDATE persons SET per_password = '2a6445462a09d0743d945ef270b9485b' AND WHERE per_email = '[email protected]'

How can I get rid of this extra 'AND'?

+3  A: 

I'd probably start with:

function update($table, $set, $where) {
  $change = array();
  foreach ($set as $k => $v) {
    $change[] = $k . ' = ' . escape($v);
  }
  $conditions = array();
  foreach ($where as $k => $v) {
    $conditions[] = $k . ' = ' . escape($v);
  }
  $query = 'UPDATE ' . $table . ' SET ' .
    implode(', ', $change) . ' WHERE ' .
    implode(' AND ', $conditions);
  mysql_query($query);
  if (mysql_error()) {
    // deal with it how you wish
  }
}

function escape($v) {
  if (is_int($v)) {
    $v = intval($v);
  } else if (is_numeric($v)) {
    $v = floatval($v);
  } else if (is_null($v) || strtolower($v) == 'null') {
    $v = 'null';
  } else {
    $v = "'" . mysql_real_escape_string($v) . "'";
  }
  return $v;
}
cletus
I use something similar to this when I don't have access to things like the Zend Framework, and it works well.
David Caunt
A: 

It's not a solution I'm particularly proud of, but you can always add $lsQuery .= 'someField=someField'.

tstenner
Sorry but I don't understand what you mean.
sanders
@tstenner: I think you've misunderstood the question. @sanders is asking how to get rid of the AND in the SET clause, not in the WHERE clause.
Pourquoi Litytestdata
In my answer, the resulting query would've been "[..] SET per_password='something' AND someField=someField WHERE field1=1[..]", so the WHERE-clause wouldn't be affected.
tstenner
+1  A: 

If you want to keep your existing code.

$lsWhere = array();
foreach($psWhere as $lsKey => $lsValue)
{
    $lsWhere[] = $lsKey." = '".mysql_real_escape_string($lsValue)."'";
}
$lsQuery .= join(" AND ", $lsWhere);
antennen
tnx. I was looking for a solution for which I wouldn't have to change my whole update function.
sanders