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

React+PHP项目点击添加按钮后MySQL数据库重复插入两条数据问题

React+PHP食谱项目添加食谱时重复插入数据库的问题解决

我正在用React.js前端结合PHP后端开发食谱数据库项目,实现食谱的增删改查功能。当前AddRecipe组件功能基本正常,但存在一个问题:每次点击“Add Recipe”按钮,MySQL数据库中会插入两条记录——一条参数正确,另一条为空。

调试后确认handleSubmit函数仅被调用一次,尝试修改按钮类型等方法都没解决问题,最终通过在PHP接口中增加请求方法判断(仅处理POST请求)解决了重复插入的问题。

问题原因

原PHP接口没有对请求方法做校验,除了Axios发送的正常POST请求外,可能存在其他非预期请求(比如GET请求)触发了插入逻辑。当请求不是POST时,file_get_contents("php://input")无法获取有效数据,$data为空,插入的字段值就都是空字符串,从而产生空记录。

解决方案

在PHP接口中添加$_SERVER['REQUEST_METHOD'] === 'POST'的判断,仅处理POST请求,其他请求直接返回错误,避免非预期的插入操作。

相关代码

React前端组件(AddRecipe.js)

//AddRecipe.js
import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';

const AddRecipe = () => {
  const [title, setTitle] = useState('');
  const [ingredients, setIngredients] = useState('');
  const [instructions, setInstructions] = useState('');
  const isSubmittingRef = useRef(false);

  useEffect(() => {
    console.log('Rendering AddRecipe component');
  }, []);

  const addRecipe = () => {
    isSubmittingRef.current = true;
    console.log('Data to be sent:', { title, ingredients, instructions });
    axios
      .post('http://localhost/add_recipe.php', {
        title,
        ingredients,
        instructions,
      })
      .then((response) => {
        console.log('Successful response:', response.data);
      })
      .catch((error) => {
        console.error('There was an error!', error);
      })
      .finally(() => {
        isSubmittingRef.current = false;
      });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!isSubmittingRef.current) {
      addRecipe();
    }
  };

  return (
    <div>
      <h2>Add Recipe</h2>
      <form onSubmit={handleSubmit}>
        <label>Title:</label>
        <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />

        <label>Ingredients:</label>
        <textarea value={ingredients} onChange={(e) => setIngredients(e.target.value)}></textarea>

        <label>Instructions:</label>
        <textarea value={instructions} onChange={(e) => setInstructions(e.target.value)}></textarea>

        <button type="submit" disabled={isSubmittingRef.current}>
          Add Recipe
        </button>
      </form>
    </div>
  );
};

export default AddRecipe;

原PHP接口代码(存在问题)

# 原add_recipe.php(会导致重复插入)
<?php
include 'db_connection.php';

$data = json_decode(file_get_contents("php://input"));

$title = $data->title;
$ingredients = $data->ingredients;
$instructions = $data->instructions;

$sql = "INSERT INTO recipes (title, ingredients, instructions) VALUES ('$title', '$ingredients', '$instructions')";
if ($conn->query($sql) == TRUE) {
    echo json_encode(["message" => "Recipe added successfully"]);
} else {
    echo json_encode(["error" => "Error: " . $sql, "<br>" . $conn->error]);
}

$conn->close();
?>

修改后的PHP接口代码(解决问题)

# 修改后的add_recipe.php(修复重复插入)
<?php
include 'db_connection.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents("php://input"));

    $title = $data->title;
    $ingredients = $data->ingredients;
    $instructions = $data->instructions;

    $sql = "INSERT INTO recipes (title, ingredients, instructions) VALUES ('$title', '$ingredients', '$instructions')";
    if ($conn->query($sql) == TRUE) {
        echo json_encode(["message" => "Recipe added successfully"]);
    } else {
        echo json_encode(["error" => "Error: " . $sql, "<br>" . $conn->error]);
    }
} else {
    echo json_encode(["error"=> "仅支持POST请求"]);
}

$conn->close();
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:17:54