Skip to content
Advertisement

Insert into SQL database from React front end

Im trying to insert some data into a SQL table but Im getting nothing from the front or back end I have tried console.log at various intervals but I cant seem to get data from either side.

For reference I have table called products with three columns id, name, image Im trying to insert both name and image with a button click. Additionally im trying to delete data thats been inserted and that also does nothing.

I have already achieved this with one table but that table only has one column.

Heres the front end

import React, {useState, useEffect} from 'react';
import axios from 'axios';
import Helmet from 'react-helmet';

export default function Products() {
    const [rows, setRows] = useState([]);
    const [name, setName] = useState('');
    const [src, setSrc] = useState('');

    useEffect(() => {
        axios.get('/products/get')
            .then(res => {
                setRows(res.data);
            }).catch(err => {
            console.log(err);
        });
    });

    //Insert into database api request
    const insertRow = () => {
        axios.post('/products/insert', {
            row: {name: name, image: src}
        });

        console.log(name, src);
    };

    //Delete from database api request
    const deleteRow = () => {
        axios.delete(`/products/delete/${name, src}`);
    };

    return (
        <>
            <Helmet>
                <title>Title | products</title>
            </Helmet>
            
            <div className="pt-36 sm:pt-44 pb-20 md:pb-48 max-w-[1200px] mx-5 lg:mx-auto">
                <input className="border-2 border-black p-1" type="text" onChange={setName} />
                <input className="border-2 border-black p-1" type="text" onChange={setSrc} />;

                <button className="border-2 border-l-0 border-black p-1" onClick={insertRow}>Submit</button>

                {rows.map((row, index) => {
                    return (
                        <div key={index}>
                            <p>{row.name}</p>
                            <img src={row.image} alt={row.name} />
                            <button onClick={() => {deleteRow(row)}}>Delete</button>
                        </div>
                    )
                })}
            </div>
        </>
    );
};

And the back end

const express = require('express');
const cors = require('cors');
const db = require('./config/db');

const app = express();
const PORT = process.env.PORT || 8080;

//Dependencies
app.use(express.json());
app.use(cors());

//#region Products table
    app.get('/products/get', (req, res) => {
        const selectAll = 'SELECT * FROM products';

        db.query(selectAll, (err, rows) => {
            if (err) throw err;
            res.send(rows);
        });
    });

    //Insert into database
    app.post('/products/insert', (req, res) => {
        const row = req.body.row; //Row to insert
        const insertRow = "INSERT INTO products (name, image) VALUES (?, ?)"; //Insert query

        db.query(insertRow, [row], (err, rows) => { //Insert row into database
            if (err) throw err;
            console.log('inserted: ' + row); //Print row inserted
        });

        console.log(row);
    });

    //Delete from database
    app.delete('/products/delete/:row', (req, res) => {
        const row = req.params.row;
        const deleteRow = "DELETE FROM products WHERE name = ?";

        db.query(deleteRow, [row], (err, rows) => {
            if (err) throw err;
            console.log('deleted: ' + row);
        });
    });
//#endregion

//Server port
app.listen(process.env.PORT || PORT, () => {
    console.log('Server started on port ' + PORT);
});

Advertisement

Answer

You have a problem in your frontend code, the setName and setSrc are done improperly:

return (
    <input className="border-2 border-black p-1" type="text" onChange={setName} />
    <input className="border-2 border-black p-1" type="text" onChange={setSrc} />;
)

Here’s how it should be:

return (
    <input className="border-2 border-black p-1" type="text" onChange={(event) => setName(event.target.value)} />
    <input className="border-2 border-black p-1" type="text" onChange={(event) => setSrc(event.target.value)} />;
)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement