我正在尝试创建一个灵活的更新查询。我现在有这样的东西:
$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/