为什么我的 PDO 查询不能使用 fetch() 执行?



我试图通过一个按钮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值。点击按钮,我看到"成功更改"但是,在控制台上,数据库上的值不会改变。我哪里做错了?

正如@esqew所提到的,!$stmt没有做我所期望的,相反,我需要@aynber解决方案来检查是否有任何行被更改。

我发现错误是在传递给查询的值,而不是因为我传递的值已经存在于返回'0行更改'的数据库中。

最新更新