article

Wednesday, July 17, 2024

Next.js 14 Fetch data from the database using PHP API Mysql

Next.js 14 Fetch data from the database using PHP API Mysql

Install nextjs npx create-next-app@latest https://nextjs.org/docs/getting-started/installation
app\page.js
//app\page.js 
import UserDataComponent from '@/components/UserDataComponent'
import { Suspense } from "react";

export default async function Home() {
  return (
    <div className="w-screen py-20 flex justify-center flex-col items-center">
      <div className="flex items-center justify-between gap-1 mb-5">
        <h1 className="text-4xl font-bold">Next.js 14 Fetch data from the database using PHP API Mysql</h1>
      </div>    
      <div className="overflow-x-auto">
        <Suspense fallback="Loading...">
            <UserDataComponent/>
          </Suspense>
      </div>  
    </div>
  );
}
components\UserDataComponent.js
//components\UserDataComponent.js
"use client";

import Axios from 'axios';
import React, { useEffect, useState } from "react";

const UserDataComponent = () => {

    const [userData,setUserData]= useState([]);

    useEffect(() => {
        const fetchUsers = async () => {
            Axios.get('http://localhost:8888/devproject/getUserData.php')
            .then(function (data) {
                //handle success
                console.log('userData',data)
                setUserData(data.data)
            })
            .catch(function (error) {
                //handle error
                console.log(error)
            });
        }
        fetchUsers()
    }, [])
    

    return (
        <div>
        <h1>User  List</h1>
        <table className="table table-zebra">
        <thead className="text-sm text-gray-700 uppercase bg-gray-50">
            <tr>
            <th className="py-3 px-6">#</th>
            <th className="py-3 px-6">Name</th>
            <th className="py-3 px-6">Email</th>
            <th className="py-3 px-6">Password</th>
            </tr>
        </thead>
        <tbody>
            {userData.map((rs, index) => (
            <tr key={rs.id} className="bg-white border-b">
                <td className="py-3 px-6">{rs.id}</td>
                <td className="py-3 px-6">{rs.name}</td>
                <td className="py-3 px-6">{rs.email}</td>
                <td className="py-3 px-6">{rs.password}</td>
            </tr>
            ))}
        </tbody>
        </table>
        </div>
    )
}

export default UserDataComponent
run C:\nextjs>npm run dev

dbcon.php
//dbcon.php
<?php
//$mysqli = new mysqli("hostName", "dbUserId", "dbPassword", "dbName");
$mysqli = new mysqli("localhost", "root", "root", "devproject");
?>
getUserData.php
//getUserData.php
<?php
 //getUserData.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

//Database Connection
include 'dbcon.php';
$value=array();
$Sql_Query ="SELECT * from users";
$result = $mysqli->query($Sql_Query);
if (@$result->num_rows >0) {
    while($row[] = $result->fetch_assoc()) {
        $item = $row;
        $json = json_encode($item,JSON_PRETTY_PRINT);
    }
    echo @$json;
} else {
    echo json_encode($value,JSON_PRETTY_PRINT);;
}

$mysqli->close();
?>

Related Post