Install nextjs npx create-next-app@latest https://nextjs.org/docs/getting-started/installation
app\page.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //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> ); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | //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 () => { .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 |
dbcon.php
1 2 3 4 5 | //dbcon.php <?php //$mysqli = new mysqli("hostName", "dbUserId", "dbPassword", "dbName"); $mysqli = new mysqli( "localhost" , "root" , "root" , "devproject" ); ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //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(); ?> |