如何在 React 和 PHP 中获取数据?

问题描述 投票:0回答:1

我编写了我的 React 应用程序,通过 PHP 将数据保存在数据库中,但它在控制台中给出了此错误,并且不保存在数据库中(我使用 xxamp):并且 tbl 表中的列名称是 isConfirmed 和 coursename。

POST http://localhost:3000/Components/saveCourses.php 404 (Not Found)
App.js:46 Fetch failed loading: POST "http://localhost:3000/Components/saveCourses.php".

在此输入图片描述

这是我的

app.js
:

import React, { useState, useEffect } from 'react';
import CourseForm from './Components/CourseForm';
import CourseList from './Components/CourseList.js';

const App = () => {
  const [courses, setCourses] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch('./Components/show.php');
      const data = await response.json();
      setCourses(data);
    } catch (error) {
      console.log('Error:', error);
    }
  };

  const addCourse = (courseName) => {
    setCourses([...courses, { name: courseName, isConfirmed: false }]);
  };

  const editCourse = (index) => {
    const newCourseName = prompt("Enter the new value:");
    if (newCourseName) {
      setCourses(courses.map((course, i) => i === index ? { ...course, name: newCourseName } : course));
    }
  };

  const deleteCourse = (index) => {
    setCourses(courses.filter((_, i) => i !== index));
  };

  const confirmCourse = (index) => {
    setCourses(courses.map((course, i) => i === index ? { ...course, isConfirmed: true } : course));
  };

  const saveCourses = async () => {
    const confirmSave = window.confirm("Are you sure you want to save the data?");
    if (confirmSave) {
      try {
        await fetch('./Components/saveCourses.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(courses)

        });
        alert("Courses saved successfully!");
      } catch (error) {
        console.error('Error:', error);
      }
    } else {
      alert("Save operation cancelled.");
    }
  };

  return (
    <div className="App">
      <CourseForm addCourse={addCourse} />
      <CourseList courses={courses} editCourse={editCourse} deleteCourse={deleteCourse} confirmCourse={confirmCourse} />
      <button onClick={saveCourses}>Save DB</button>
      <button onClick={fetchData}>Show Data</button>
      <div id="dataContainer"></div>
    </div>
  );
};

export default App;

这是 PHP 文件:

<?php


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "courses";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    echo "Connection failed: " . mysqli_connect_error();
} 


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

$values = '';
foreach ($ddd as $row) {
    $values .= "('$row[name]', $row[isConfirmed]),";
}

$values = rtrim($values, ',');
$insertSql = "INSERT INTO tbl (coursename, isConfirmed) VALUES " . $values;

if (mysqli_query($conn, $insertSql)) {
    echo "Records saved successfully.";
} else {
    echo "Error: " . $insertSql . "<br>" . mysqli_error($conn);
}

php sql reactjs database fetch
1个回答
0
投票

正如您提到的,您正在使用 XAMPP,然后确保 saveCourses.php 放置在您的 Web 服务器(即 htDocs)可访问的目录中,并且您可以将 fetch 调用更新为 http://localhost/saveCourses.php

© www.soinside.com 2019 - 2024. All rights reserved.