【发布时间】:2021-11-26 18:55:06
【问题描述】:
我正在尝试通过按钮 onclick 事件执行更新语句,但使用 fetch api 运行它时没有成功。
我有这个 JavaScript 函数:
const changeProductAvailability = (id,status) => {
const formData = new FormData();
formData.append('product', id);
formData.append('able', status);
fetch("change-availability.php", {
method: "POST",
body: formData,
})
.then((response) => response.text())
.then((text) => {
console.log(text);
})
}
我在 change-availability.php 中有这个:
$query_sql = "UPDATE product SET able_to_order = :able WHERE id = :id";
$data = [
"able" => $_POST['able'],
"id" => $_POST['product']
];
$stmt = $conn->prepare($query_sql);
$stmt->execute($data);
if (!$stmt) {
echo "Error on updating"
}else{
echo "Sucessfully changed";
}
在 html 上,我有一个按钮,它使用 2 个参数调用这样的函数:
<button
class="btn <?=$row["able_to_order"] == 0 ? "btn-success" : "btn-danger" ?>"
onclick="changeProductAvailability(<?= $row['id'] .",".$row['able_to_order']?>)">
<?=$row["able_to_order"] == 1 ? "Disable" : "Enable" ?>
</button>
PDO 语句有效,因为我尝试直接打开页面并更改为数据数组上的 GET 值。单击按钮时,我会在控制台上看到“已成功更改”,但是,数据库上的值不会更改。我做错了什么?
【问题讨论】:
-
!$stmt不会像您认为的那样做。调用$stmt->execute()的返回值返回您应该测试的布尔值。 -
PDO 只会在查询失败时返回 false。如果您想查看是否有任何记录受到影响,可以查看the rowCount for affected rows。
-
好的,在您的帮助下我已经解决了。将返回消息更改为 $stmt->rowCount() 后,它返回“0 rows changed”,这让我意识到这实际上是我的查询不正确。谢谢
标签: javascript php ajax pdo fetch-api