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

PHP-PDO表单提交无报错但phpmyadmin查询不到数据库写入数据

问题原因

  • INSERT语句语法错误:字段列表缺少闭合右括号,插入值关键字应为VALUES而非VALUE
  • 预处理语句未执行:仅调用prepare()完成SQL预处理,没有执行execute()方法,插入请求未实际发送到数据库
  • 缺少请求类型判断:页面首次GET加载时直接读取$_POST变量会抛出未定义索引警告,同时会触发无数据的无效插入逻辑
  • 占位符参数缺失::image占位符没有对应赋值,你未处理上传的图片文件,也没有定义$image变量

修复后代码

<?php
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=products_crud', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 仅处理POST提交请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'];
    $description = $_POST['description'];
    $price = $_POST['price'];
    $date = date('Y-m-d H:i:s');

    // 处理图片上传,示例默认无上传则存空值,可根据需求补全上传逻辑
    $image = '';
    if (!empty($_FILES['image']['tmp_name'])) {
        // 若存图片路径,可自行补全图片移动存储、生成随机文件名的逻辑,将最终路径赋值给$image
        // 示例为存二进制内容的写法,若存路径可删除下行替换为路径处理逻辑
        $image = file_get_contents($_FILES['image']['tmp_name']);
    }

    // 修复SQL语法:字段列表补右括号,VALUE改VALUES
    $stmt = $pdo->prepare("INSERT INTO products (title, image, description, price, create_date)
        VALUES (:title, :image, :description, :price, :date)");
    
    // 绑定参数执行插入
    $stmt->execute([
        ':title' => $title,
        ':image' => $image,
        ':description' => $description,
        ':price' => $price,
        ':date' => $date
    ]);

    // 插入成功后跳转回列表页,避免重复提交
    header('Location: index.php');
    exit;
}
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <link rel="stylesheet" href="app.css">
    <title>Products CRUD</title>
</head>
<body>
    <h1>Create new product</h1>
    <form enctype="multipart/form-data" action="create.php" method="POST">
        <div class="mb-3">
            <label>Product Image</label>
            <br>
            <input type="file" name="image">
        </div>
        <div class="mb-3">
            <label>Product Title</label>
            <input type="text" name="title" class="form-control" required>
        </div>
        <div class="mb-3">
            <label>Product Description</label>
            <textarea class="form-control" name="description"></textarea>
        </div>
        <div class="mb-3">
            <label>Product Price</label>
            <input type="number" step=".01" name="price" class="form-control" required>
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 23:54:03