sanders
sanders

Reputation: 10898

Creating a flexible update query

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'?

Upvotes: 1

Views: 404

Answers (3)

tstenner
tstenner

Reputation: 10291

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

Upvotes: 0

runfalk
runfalk

Reputation: 1996

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

Upvotes: 2

cletus
cletus

Reputation: 625097

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

Upvotes: 3

Related Questions