在 PHP 中使用 MySQLi 是否可以在不知道字段名称、字段数量及其值的情况下使用数组更新表。
我已经尝试使用准备好的语句在键和值字段 (?=?) 上插入问号。我在想是否可以在更新查询中使用 () VALUES () 我可能有一个解决方案,但我猜不存在这样的事情。
看看我的脚本:
<?php
class UserHandler {
public function updateUserData($array, $id) {
global $mysqli;
$stmt = $mysqli->prepare("UPDATE users SET ?=? WHERE id = ?");
$stmt->bind_param('ssi', $array[0], $array[1], $id);
$stmt->execute();
return true;
}
}
$users = new UserHandler;
?>
我希望用法是这样的:
<?php
$users->updateUserData(array(
'firstname' => 'Wanda',
'lastname' => 'Merritt',
'state' => 'IN'
'address' => '693 Pearcy Avenue',
'zipcode' => 46625,
), 45);
$users->updateUserData(array(
'firstname' => 'Stanley',
'lastname' => 'Lewis',
'password' => '123123'
), 159);
?>
最佳答案
一个查询,带有准备好的语句:
public function updateUserData($array, $id) {
global $mysqli;
$query = "UPDATE `users` SET ";
$parts = array();
foreach ($array as $key => $value) {
$parts[] = "`" . $key . "` = ?";
}
$query = $query . implode(",", $parts) . " WHERE id = ?";
$stmt = $mysqli->prepare($query);
foreach ($array as $key => $value) {
$stmt->bind_param('s', $value);
}
$stmt->bind_param('i', $id);
$stmt->execute();
return true;
}
这确实假定所有值都是字符串。
关于php - 使用数组更新 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19157510/