You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数据库数据无法更新求助:更新提示成功但数据未变更

更新操作提示成功但数据库无变化的问题排查与修复

核心问题分析

你的代码存在两处变量匹配错误,导致更新语句无法定位到目标数据行:

  1. 表单提交的ID字段名不匹配
    在edit-code.php中,隐藏字段的name属性是id:
<input type="hidden" name="id" value="<?= $result->id; ?>" class="form-control" id="id">

但update.inc.php中错误地尝试获取不存在的$_POST["code_id"],导致$code_id变量为空:

$code_id = $_POST["code_id"]; // 错误:表单中无name="code_id"的字段
  1. 更新语句的ID参数未正确赋值
    update.inc.php的$data数组中,使用了未定义的变量$id,而非已经获取到的$code_id:
":id" => $id, // 错误:$id从未定义

修复后的update.inc.php关键代码

<?php
session_start();
include("connect.inc.php");

if(isset($_POST["update-code-btn"])) {
    // 修正1:获取表单中正确的ID字段
    $code_id = $_POST["id"];
    $service = $_POST["service"];
    $discount = $_POST["discount"];
    $expiry = $_POST["expiry"];
    $code = $_POST["code"];

    try {
        $query = "UPDATE codes SET service=:service, discount=:discount, expiry=:expiry, code=:code WHERE id=:id LIMIT 1";
        $stmt = $conn->prepare($query);

        $data = [
            ":service" => $service,
            ":discount" => $discount,
            ":expiry" => $expiry,
            ":code" => $code,
            ":id" => $code_id, // 修正2:使用正确的变量传递ID参数
        ];

        $query_execute = $stmt->execute($data);

        if($query_execute){
            $_SESSION["message"] = "Updated Successfully";
            header("Location: ../view.php");
            exit(0);
        } else {
            $_SESSION["message"] = "Data Update Failed";
            header("Location: ../view.php");
            exit(0);
        }

    } catch(PDOException $e) {
        echo $e->getMessage();
    }
}

额外排查建议

开发环境下可以开启PHP错误提示,快速定位未定义变量这类问题:

error_reporting(E_ALL);
ini_set('display_errors', 1);

内容的提问来源于stack exchange,提问作者user19468046

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:01:14