我正在尝试创建灵活的更新查询。我现在有这样的事情:
$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));
但是当我在屏幕上打印查询时,我得到的结果是:
UPDATE persons SET per_password = '2a6445462a09d0743d945ef270b9485b' AND
WHERE per_email ='bla@gmail.com'
如何摆脱这种额外的'AND'?
答案 0 :(得分:3)
我可能会从:
开始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;
}
答案 1 :(得分:2)
如果您想保留现有代码。
$lsWhere = array();
foreach($psWhere as $lsKey => $lsValue)
{
$lsWhere[] = $lsKey." = '".mysql_real_escape_string($lsValue)."'";
}
$lsQuery .= join(" AND ", $lsWhere);
答案 2 :(得分:0)
这不是我特别自豪的解决方案,但您可以随时添加$lsQuery .= 'someField=someField'
。