让我说我有和像这样的数组
$array= Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
此数组中的键是表中列的名称,值是我需要更新的列的值。 我想根据键和值更新表。 我正在使用ADODB 请帮帮我
答案 0 :(得分:2)
试试这个:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
$sql .= $key . " = " . $value . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
当然还有WHERE
子句:
$sql .= " WHERE condition = value";
你会得到字符串:
UPDATE table SET id = 3, name = NAME, age = 12 WHERE condition = value
L.E:您可能需要向字符串添加撇号,因此我必须将代码更改为以下内容:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= " WHERE condition = value";
将产生这个:
UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE condition = value
L.E 2:如果你想在你的条件中使用id列,代码就变成了这样:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if($key == 'id'){
$sql_condition = " WHERE " . $key . " = " . $value;
continue;
}
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= $sql_condition;
将产生这个结果:
UPDATE table SET name = 'NAME', age = 12 WHERE id = 3
希望这有帮助! :d
答案 1 :(得分:0)
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
来源:https://stackoverflow.com/a/7884331/3793639
要检查的其他来源。 PHP SQL Update array和Simple UPDATE MySQl table from php array
答案 2 :(得分:0)
您可以使用类似的东西来实现这一目标:
foreach($values as $value) {
if(!key_exists($value, $item)) {
return false;
}
$table->{$value} = $items[$value];
}
答案 3 :(得分:0)
假设密钥索引始终为id且adodb可以使用命名占位符,则可以执行以下操作:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$set = array();
$data = array();
while(list($key,$value)=each($array)) {
$data[':'.$key] = $value;
if($key!='id') {
$set[] = $key . ' = :' . $key;
// if no placeholders use $set[] = $key . " = '" . database_escape_function($value) . "'";
}
}
$sql = "UPDATE table SET ".implode($set, ',')." WHERE id=:id";
//$data is now Array(':id'=>'3', ':name'=>'NAME', ':age'=>'12');
//$sql is now "UPDATE table SET name=:name, age=:age WHERE id=:id";
$stmt = $DB->Prepare($sql);
$stmt = $DB->Execute($stmt, $data);