我有这段代码来更新数据库中的记录,通常我只会更新一列,例如:在阵列上我列出了6列,我只想更新列keywords
,而另一列专栏应该不会受到影响。
使用此代码,我可以更新记录,但不能更新especifc列,因为如果我在input name="keywords"
上写东西,而在其他输入上不写任何内容,则这些输入中的列值将被替换为我的数据库。
我的问题是:
如何在不影响其他列的情况下更新列?
if(isset($_POST["updateBTN"])){
$insert_data = array(
':title' => $_POST['title'],
':keywords' => $_POST['keywords'],
':img' => $_POST['img'],
':widht' => $_POST['widht'],
':status' => $_POST['status'],
':name' => $_POST['name'],
':height' => $_POST['height']
);
$query = "UPDATE table SET keywords = :keywords, img = :img, widht = :widht, status = :status, name = :name, height = :height WHERE title = :title";
$statement = $conn->prepare($query);
$statement->execute($insert_data);
}
html:
<form method="post">
<div>
<input type="text" name="title">
<span data-placeholder="Title"></span>
</div>
<div>
<input type="text" name="keywords">
<span data-placeholder="keywords"></span>
</div>
.
.
.
<button type="submit" name="updateBTN">Send</button>
</form>
答案 0 :(得分:1)
您可以更改SQL查询以仅更新具有其数据的列,或者使用从数据库中检索到的值填充$insert_data
中的所有未定义值。第一个可能是更好的主意,但第二个则更易于实现。
我没写过PHP,但是也许是这样的:
if(isset($_POST["updateBTN"])) {
$query = "SELECT title, keywords, img, widht, staus, name, height FROM table WHERE title = :title";
$stmt = $conn->prepare($query);
$stmt->execute(array(":title" => $_POST['title']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$insert_data = array(
':title' => $_POST['title'] ? $_POST['title'] : $row['title'],
':keywords' => $_POST['keywords'] ? $_POST['keywords'] : $row['keywords'],
...
);
$query = "UPDATE table SET keywords = :keywords, img = :img, widht = :widht, status = :status, name = :name, height = :height WHERE title = :title";
$statement = $conn->prepare($query);
$statement->execute($insert_data);
}
答案 1 :(得分:0)
假设您不想将任何列设置为NULL
值,则可以使用COALESCE()
:
UPDATE table
SET keywords = COALESCE(:keywords, keywords),
img = COALESCE(:img, img),
widht = COALESCE(:widht, widht),
status = COALESCE(:status, status),
name = COALESCE(:name, name),
height = COALESCE(:height height)
WHERE title = :title;
答案 2 :(得分:0)
看看是否可行
UPDATE table
SET keywords = :keywords,
img = CASE WHEN img IS NOT NULL THEN img ELSE :img END,
widht = CASE WHEN widht IS NOT NULL THEN widt ELSE :widht END,
status = CASE WHEN status IS NOT NULL THEN status ELSE :status END,
name = CASE WHEN name IS NOT NULL name ELSE :name END,
height = CASE WHEN height IS NOT NULL THEN height ELSE :height END
WHERE title = :title;