php - 创建灵活的更新查询

标签 php mysql sql-update

我正在尝试创建一个灵活的更新查询。我现在有这样的东西:

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

但是当我在屏幕上打印我的查询时,我得到类似的东西:

更新 persons SET per_password = '2a6445462a09d0743d945ef270b9485b' AND WHERE per_email = 'bla@gmail.com'

我怎样才能去掉这个额外的“AND”?

最佳答案

我可能会开始:

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

关于php - 创建灵活的更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/694437/

相关文章:

php - jQuery Highcharts : change chart type using dropdown list

mysql - 仅当该行缺少特定值时才返回该行的查询

java - 在 hibernate native 查询中设置列表不起作用

mysql - 更新 SQL 中的完整记录?

mysql - 仅更新用户条目的最后一行

javascript - 如何在通过ajax发送值时处理编码

php - 如何从 PHP 将 MySql SQL_MODE 设置为 ANSI

php - 在 sql 表的所有行之间进行选择的 Jquery/Ajax 对话框

php - ORDER BY number_column DESC : why does a smaller number come before a larger?

MySql转换问题: from UNIX_TIMESTAMP to INT(11)