React JS + MySQL (xampp) How to connection. CRUD system

![image-2.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/92f64441-d321-dd43-7185-6ceda3e205a3.png)

# Reference youtube
https://youtube.com/playlist?list=PLpPqplz6dKxW42HMj6iuiA45d4xqP9ICq

# Install xampp

https://www.apachefriends.org/jp/index.html

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/cc495fe3-1128-c180-2511-5b56671e3224.png)


# MySQL running

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/e81ae526-1201-dbee-e15c-86994d06c3ed.png)

# Install Module
```terminal:terminal
 npm install cors dotenv express mysql2 nodemon
```

# Scripts
```json:package.json
   "scripts": {
    "dev": "nodemon index.js"
  }
```

# MySQL connection
```javascript:database.js
    const mysql = require('mysql2')

    const connectDB = mysql.createPool({
         host: 'localhost', // host name
         user: 'root', // user name
         password: "", // password
         database: "curd_database" // database name
    });

    module.exports = connectDB
    
```

# phpMyAdmin
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/8257a67a-d053-1e56-bbef-0114aea38447.png)
# Table name and structure
> **table name**
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/bd9fb019-9b42-52d4-434b-4dada05ccf8c.png)

> **table structure**
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/04daa488-0422-3a94-382e-f78766d42c10.png)

# CRUD system
```javascript:index.js
    require("dotenv").config();
    const express = require("express");
    const app = express();
    const PORT = process.env.PORT || 5000;
    const cors = require("cors");
    const connectDB = require("./database/database");
    
    app.use(express.urlencoded({ extended: false }));
    app.use(express.json());
    app.use(cors());
    

    // get all data
    app.get("/api/get", (req, res) => {
      const sqlSelect = "SELECT * FROM movie_reviews";
      connectDB.query(sqlSelect, (err, result) => {
        res.json(result);
      });
    });
    
    // create new data
    app.post("/api/insert", (req, res) => {
      const movieName = req.body.movieName;
      const movieReview = req.body.movieReview;
    
      const sqlInser =
        "INSERT INTO movie_reviews (movieName, movieReview) VALUES (?, ?)";
      connectDB.query(sqlInser, [movieName, movieReview], (err, result) => {
        console.log(err);
      });
    });
    
    // delete a data
    app.delete("/api/delete/:id", (req, res) => {
      const id = req.params.id;
    
      const sqlDelete = "DELETE FROM movie_reviews WHERE id = ?";
      connectDB.query(sqlDelete, id, (err, result) => {
        if (err) {
          console.log(err);
        }
      });
    });
    
    // update a data
    app.put("/api/update/:id", (req, res) => {
      const id = req.params.id;
      const movieReview = req.body.movieReview;
    
      const sqlUpdate = "UPDATE movie_reviews SET movieReview = ? WHERE id = ?";
    
      connectDB.query(sqlUpdate, [movieReview, id], (err, result) => {
        console.log(err);
      });
    });
    
    app.listen(PORT, (req, res) => {
      console.log(`Server is running on port ${PORT}`);
    });

```

# React (frontend)

```terminal:terminal
    npm install axios
```

```javascript:App.js
    import { useEffect, useState } from "react";
    import "./App.css";
    import axios from "axios";
    
    function App() {
      const [movieName, setMovieName] = useState("");
      const [review, setReview] = useState("");
      const [movieReviewList, setMoviewReviewList] = useState([]);
    
      const [newReview, setNewReview] = useState("");
    
      useEffect(() => {
        axios
          .get("http://localhost:5000/api/get")
          .then((response) => {
            setMoviewReviewList(response.data);
          })
          .catch((err) => {
            console.log(err);
          });
      }, [movieReviewList]);
    
      const submitReview = async (e) => {
        e.preventDefault();
        await axios
          .post("http://localhost:5000/api/insert", {
            movieName: movieName,
            movieReview: review,
          })
          .then((result) => {
            setMoviewReviewList([
              ...movieReviewList,
              { movieName: movieName, movieReview: review },
            ]);
          });
    
          
      };
    
      const deleteReview = (id) => {
        axios.delete(`http://localhost:5000/api/delete/${id}`).then((result) => {
          console.log(result);
        });
      };
    
      const updateReview = async (id) => {
        await axios
          .put(`http://localhost:5000/api/update/${id}`, {
            movieReview: newReview,
          })
          .then((result) => {
            console.log(result);
          });
    
        setNewReview("");
      };
    
      return (
        <div className="App">
          <h1>CRUD APPLICATION</h1>
    
          <div className="form">
            <label htmlFor="name">Movie Name</label>
            <input
              type="text"
              name="movieName"
              id="name"
              onChange={(e) => setMovieName(e.target.value)}
            />
            <label htmlFor="review">Review</label>
            <input
              type="text"
              name="review"
              id="review"
              onChange={(e) => setReview(e.target.value)}
            />
            <button onClick={submitReview}>Submit</button>
            <hr />
    
            {movieReviewList &&
              movieReviewList.map((val) => {
                return (
                  <div className="card" key={val.id}>
                    <h1>{val.movieName}</h1>
                    <p>{val.movieReview}</p>
                    <button
                      onClick={() => {
                        deleteReview(val.id);
                      }}
                    >
                      Delete
                    </button>
                    <input
                      type="text"
                      id="updateInput"
                      onChange={(e) => setNewReview(e.target.value)}
                    />
                    <button
                      onClick={() => {
                        updateReview(val.id);
                      }}
                    >
                      Update
                    </button>
                  </div>
                );
              })}
          </div>
        </div>
      );
    }
    
    export default App;

```

# Result
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/668afce3-5c4e-b611-b7e0-533da05959e7.png)