Adding Data to MySQL Database from NextJS Form问题

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

我想尝试添加一个新表单,将某些产品添加到我拥有的 MySQL 数据库中,但我不确定如何创建该表单。我有我的 API 和特定页面,显示这里当然显示的产品。

import React from "react";
import { useEffect, useState } from "react";
import moment from 'moment';
import { BiPlus } from "react-icons/bi";
import Link from 'next/link';

export default function Home() {
    const[dataResponse, setdataResponse] = useState([]);
    useEffect(() => {
        async function getPageData() {
            const apiUrlEndpoint = 'http://localhost:3000/api/games';
            const response = await fetch(apiUrlEndpoint);
            const res = await response.json();
            console.log(res.games);
            setdataResponse(res.games);
        }
        getPageData();
    }, []);
    
    return (
        <div className='bg-gray-100 min-h-screen'>
            <Link href='/newgame'>
                <div className='bg-gray-100 hover:bg-gray-200 cursor-pointer my-4 p-3 rounded-lg inline-block'>
                    <BiPlus size={20} />
                    Click here to add a game
                </div> 
            </Link>
            {dataResponse.map((games) => {
                var d = new Date(games.DateWhenAdded);
                var now = moment(d).format('l');
                return (
                    <div key= {games.ProductID}>
                        <div>{games.ProductName}</div>
                    <div>
                        <img src={games.ProductImage} width="400" height="400" alt=""/>
                    </div>
                        <div>
                            {games.ProductDescription}
                        </div>
                    <div>
                         Product added on: {now}
                    </div>
                    <div>
                        Product price: ${games.ProductPrice}
                    </div>
                </div>   
             )
            })}
    </div>
);
}

API在这里:

import mysql from "mysql2/promise";
import moment from 'moment';


 export default async function handler(req, res) {
    const dbconnection = await mysql.createConnection({
        host: "localhost",
        database: "onlinestore",
        port: 3306,
        user: "root",
        password: "Jennister123!",
    });
    try {
        const query = "SELECT ProductID, ProductName, ProductDescription, ProductImage, ProductPrice, DateWhenAdded FROM games"
        const values = [];
        const[data] = await dbconnection.execute(query, values);
        console.log(data);
        dbconnection.end();
        data.forEach((games) => {
            games.ProductImage = "data:image/webp;base64," + games.ProductImage.toString('base64');
        }
        );
        data.forEach((games) => {
            // Fixes date issue
            var d = new Date(games.DateWhenAdded);
            var now = moment(d).format('l');
            console.log(now);
        }
        );
        res.status(200).json({ games: data });

    } catch (error) {
        res.status(500).json({ error: message });
    }
 }

我必须使用 PHP 脚本来执行此操作,还是可以在 JSX 文件上执行?我将如何制作表格,因为我也需要涉及“日期”和“图像”属性?

更新:

我有它的 PHP 脚本,但我不确定如何为它制作页面。如果我纯粹做一个HTML页面,我是访问不了的。有一张图片,一个“DD/MM/YYYY”格式的日期,还有一个 Decimal 价格,以及一个 int 主键(ID)。

<?php
$servername='localhost';
$username='root';
$password='Jennister123!';
$dbname='onlinestore';
$conn = mysqli_connect($servername,$username,$password,$dbname);
if(!$conn){
    die("ERROR: Could not connect".mysql_error());
}
if(isset($_POST['submit'])){
    $productid = $_POST['ProductID'];
    $productname = $_POST['ProductName'];
    $productdescription = $_POST['ProductDescription'];
    $productimage = $_POST['ProductImage'];
    $productprice = $_POST['ProductPrice'];
    $productdate = $_POST['DateWhenAdded'];

    $sql = "INSERT INTO games VALUES ('$productid','$productname','$productdescription','$productimage','$productprice','$productdate’)";
    if(mysqli_query($conn, $sql)){
        echo "Inserted record successfully";
    }
    else{
        echo "ERROR: Sorry :".$sql."".mysqli_error($conn);
    }
    mysqli_close($conn);
}
?>
php mysql database next.js add
© www.soinside.com 2019 - 2024. All rights reserved.