Create an account


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 19,395
» Latest member: GulaabJaamun
» Forum threads: 21,153
» Forum posts: 21,719

Full Statistics

Online Users
There are currently 479 online users.
» 0 Member(s) | 476 Guest(s)
Baidu, Bing, Google

 
  [Tut] ChatGPT 5.1 vs Gemini Banana Pro – Which Creates the Best Fake Monet?
Posted by: xSicKxBot - 10 hours ago - Forum: Python - No Replies

[Tut] ChatGPT 5.1 vs Gemini Banana Pro – Which Creates the Best Fake Monet?

I just finished this video comparing which AI model is better in building a Monet clone image:





This is the first image generated by ChatGPT 5.1:


This one nails the sunny summer vibe with those bright colors, but it’s honestly way too orange and saturated to pass for a real Monet. The generic ‘ART’ and ‘CAFFE’ signs look kind of fake, like something you’d find on a jigsaw puzzle rather than in a museum. It’s a pretty picture, but it feels more like modern home decor than a 19th-century masterpiece.


This is the second image generated by Google Gemini Banana Pro:


This one is much closer to the real deal, capturing that classic hazy look and the specific blue shadows that Monet actually used. It falls apart a bit when you zoom in on the weird, gibberish text and the blurry faces, which are dead giveaways for AI. Still, if you squint, this one definitely wins for feeling the most like an actual historical painting.

The post ChatGPT 5.1 vs Gemini Banana Pro – Which Creates the Best Fake Monet? appeared first on Be on the Right Side of Change.



https://www.sickgaming.net/blog/2025/12/...ake-monet/

Print this item

  [Tut] How to Build a React Data Table with Server-Side Pagination, Sorting and Search
Posted by: xSicKxBot - 10 hours ago - Forum: PHP Development - No Replies

[Tut] How to Build a React Data Table with Server-Side Pagination, Sorting and Search

by Vincy. Last modified on October 29th, 2025.

The React TanStack table is a great tool for displaying an elegant view of data table. It provides enriched features to build list with impressive user experience.

This tutorial uses Server-side data fetching and rendering, searching and sorting features.

A shopping cart product table is created in the backend. It has basic details to be listed in a tabular form. The React app connects to the PHP API to connect this database to fetch the rows.

The React TanStack data table shows these data rows in the front end as shown below.

react data table db rows

Setting up the React TanStack table example code


This command is used to install the React TanStack data table library.

npm install @tanstack/react-table

This will add the following library reference to the application’s package config.

npm install @tanstack/react-table "dependencies": { "@tanstack/react-table": "^8.21.3", ... ... },

If you are going to run this example in your environment, follow the below steps to set up. It has all the build required for the React TanStack data table rendering.

  1. Download and extract the React project bundle.
  2. Go to the React project directory by cd react-data-table-server-side-pagination-sorting-search
  3. Run npm install to create node_modules.
  4. Copy /api/react-product-table-api/ to your PHP root and configure in React JSX.
  5. Create database db_shopping_cart and import sql/database.sql

Then, start the dev server by using npm run dev.

How to initiate React TanStack data table?


This is to initiate React TabStack library using useReactTable. It adds the raw data reference to the TanStack library row column object to render data.

Part of TanStack.jsx

import { useEffect, useState, useCallback } from "react";
import axios from "axios";
import { useReactTable, getCoreRowModel, getSortedRowModel, flexRender,
} from "@tanstack/react-table";
import "./TanStack.css"; const TanStack = () => { const [data, setData] = useState([]); const [search, setSearch] = useState(""); const [page, setPage] = useState(1); const [limit, setLimit] = useState(5); const [total, setTotal] = useState(0); const [sortBy, setSortBy] = useState("id"); const [order, setOrder] = useState("asc"); ... //Fetch Data ... useEffect(() => { fetchData(); }, [fetchData]); const columns = [ { header: "S.No", accessorKey: "sno", cell: (info) => (page - 1) * limit + info.row.index + 1, }, { header: "Title", accessorKey: "title", cell: (info) => info.getValue(), }, { header: "Price", accessorKey: "price", cell: (info) => `$${info.getValue()}`, }, { header: "Category", accessorKey: "category", cell: (info) => info.getValue(), }, ]; const table = useReactTable({ data, columns, getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), }); ... ...
}

Designing the table layout and components


There are three major UI parts in this React data table example.

  1. The tabular view.
  2. Search bar.
  3. Footer pagination component.

1. The tabular view


react tanstack table filter

Table header - Part of TanStack.jsx

<th key={header.id} className={alignClass} on‌Click={() => key !== "sno" && handleSort(key) } style={{ cursor: key === "sno" ? "default" : "pointer", }}
>
{flexRender(header.column.columnDef.header, header.getContext())} {key !== "sno" && sortBy === key && (order === "asc" ? ( <img src="/icons/up.svg" alt="asc" style={{ width: "14px", height: "14px", marginLeft: "5px", verticalAlign: "middle", }} /> ) : ( <img src="/icons/down.svg" alt="desc" style={{ width: "14px", height: "14px", marginLeft: "5px", verticalAlign: "middle", }} /> ))}
</th>

This section has the TanStack script for iterating the table row array using table.gerRowModel() reference.

The flexRender function loads the table cell data in a row.

Table body rows in TanStack.jsx

<tbody> {table.getRowModel().rows.length > 0 ? ( table.getRowModel().rows.map((row) => ( <tr key={row.id}> {row.getVisibleCells().map((cell) => { const key = cell.column.columnDef.accessorKey; const alignClass = key === "price" ? "price" : key === "sno" ? "center" : ""; return ( <td key={cell.id} className={alignClass}> {flexRender(cell.column.columnDef.cell, cell.getContext())} </td> ); })} </tr> )) ) : ( <tr> <td colSpan={columns.length}>No data found</td> </tr> )}
</tbody>

2. Search Container


It is a usual HTML input that sets the search keyword on-change. When the search is on, it resets the current-page value back to 1.

Search input JSX in TanStack.jsx

<div className="search-container"> <img src="/icons/search.svg" alt="search" className="search-icon" /> <input type="text" placeholder="Search by title..." value={search} on‌Change={(e) => { setSearch(e.target.value); setPage(1); }} className="search-input" />
</div>

3. Pagination


This component returns JSX with numbered buttons with a previous-next pagination link to move the row pointer back and forth.

Pagination JSX

<div className="pagination-container"> <button className="pagination-btn" on‌Click={() => setPage((prev) => Math.max(prev - 1, 1))} disabled={page === 1} > <img src="/icons/back.svg" alt="Previous" className="pagination-icon" /> Prev </button> <span className="pagination-info"> Page {page} of {totalPages || 1} </span> <button className="pagination-btn" on‌Click={() => setPage((prev) => (prev < totalPages ? prev + 1 : prev))} disabled={page >= totalPages} > Next <img src="/icons/forward.svg" alt="Next" className="pagination-icon" /> </button> <select value={limit} on‌Change={(e) => { setLimit(Number(e.target.value)); setPage(1); }} className="pagination-select" > {[5, 10, 20, 50].map((num) => ( <option key={num} value={num}> {num} / page </option> ))} </select>
</div>

paginated results with react data table

Fetching Data from the Server API


This is the place to configure the server-side API URL to connect to the database for displaying dynamic grid. It sets the data array for the TanStack initiation.

This example has a single endpoint that receives all the search, sort and pagination inputs. The following React useCallback() passes these parameters to the API.

The React callback hook sets the raw data for the TanStack’s getCoreRowModel block to build a table row instance.

Part of TanStack.jsx

const fetchData = useCallback(async () => { try { const res = await axios.get("http://localhost/react-product-table-api/products.php", { params: { search, page, limit, sortBy, order }, }); const fetchedData = res.data.data || res.data.products || []; setData(fetchedData); setTotal(res.data.total || 0); } catch (err) { console.error("Error fetching data:", err); }
}, [search, page, limit, sortBy, order]);

Below PHP script shows how to process a request from the allowed React origin. This PHP service prepares the SELECT query based on the search keyword, current page and sorting column & order passed from the React frontend.

react-product-table-api/products.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
require_once "db.php"; $page = $_GET['page'] ?? 1;
$limit = $_GET['limit'] ?? 5;
$search = $_GET['search'] ?? '';
$sortBy = $_GET['sortBy'] ?? 'id';
$order = $_GET['order'] ?? 'asc';
$offset = ($page - 1) * $limit; $allowedSort = ['id', 'title', 'price', 'category'];
$allowedOrder = ['asc', 'desc']; if (!in_array($sortBy, $allowedSort)) $sortBy = 'id';
if (!in_array(strtolower($order), $allowedOrder)) $order = 'asc'; $sql = "SELECT * FROM products WHERE title LIKE ? ORDER BY $sortBy $order LIMIT ?, ?";
$stmt = $conn->prepare($sql);
$searchParam = "%$search%";
$stmt->bind_param("sii", $searchParam, $offset, $limit);
$stmt->execute();
$result = $stmt->get_result(); $data = [];
while ($row = $result->fetch_assoc()) { $data[] = $row;
} $countSql = "SELECT COUNT(*) AS total FROM products WHERE title LIKE ?";
$countStmt = $conn->prepare($countSql);
$countStmt->bind_param("s", $searchParam);
$countStmt->execute();
$countResult = $countStmt->get_result()->fetch_assoc(); echo json_encode([ "products" => $data, "total" => $countResult["total"]
]);
?>

Conclusion


This example built a front end React data table with search, sort and pagination features. The TanStack table library provides more features apart these three features. For example, it has column ordering, row selection, resizing and more. But, we covered the prime features of this library that are need in majority of the frontend tables.

References

  1. TanStack table installation guidelines
  2. Data table design patterns

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top



https://www.sickgaming.net/blog/2025/10/...nd-search/

Print this item

  [Tut] How to ship an AI-powered project in 1 hour per day ?
Posted by: xSicKxBot - 12-07-2025, 11:31 PM - Forum: Python - No Replies

[Tut] How to ship an AI-powered project in 1 hour per day ?

A Skool group member just shared that they have a super busy schedule, bought an annual plan to explore ideas, but still struggle to ship something.

Here’s a simple 4-step process that works for me – shipping dozens of projects in the last few months:


1. Pick one small project. Keep it tiny and real:

  • Simple static website, calculator, value proposition, or
  • Tiny web app with one core feature

? One project, one month.


2. Set up once

  • Create a GitHub repo
  • Connect it to the OpenAI Codex agent: https://chatgpt.com/codex
  • (Optional) Connect GitHub to a host (Heroku/Netlify/Vercel – I use Heroku) so every push auto-deploys.

3. Make a tiny-task list. Create a Google Sheet with small, 1-hour tasks, e.g.:

  • Add an about page
  • Improve mobile layout
  • Add Google Analytics
  • Change theme color and styles
  • Add a contact form

4. Your daily 1-hour habit. Each day:

  • Pick one task
  • Ask the Codex agent to implement it (in natural language)
  • Test, tweak, iterate, commit, push

You’re not hand-coding everything – you’re simply orchestrating AI. Do this CONSISTENTLY for a month and you’ll be amazed how much you’ve shipped. ?

? If you want to accelerate your progress shipping genuinely valuable project every single month, check out my inexpensive community:


? SHIP! – One Project Per Month

The post How to ship an AI-powered project in 1 hour per day ? appeared first on Be on the Right Side of Change.



https://www.sickgaming.net/blog/2025/11/...%9f%9a%80/

Print this item

  [Tut] Send Email from React Using EmailJS (No Backend Required)
Posted by: xSicKxBot - 12-07-2025, 11:31 PM - Forum: PHP Development - No Replies

[Tut] Send Email from React Using EmailJS (No Backend Required)

by Vincy. Last modified on November 13th, 2025.

EmailJS is a cloud service that supports to enable the frontend to send email without any backend. All we need is to create an EmailJS account and configure it to the frontend application.

This tutorial shows the step-by-step procedure to learn how to enable email sending in a React application using EmialJS.

Send Email From React Using EmailJS

Steps to allow EmailJS to send mail


1. Signup with EmailJS service


First signup and login with EmailJS dashboard. It’s a free and enables mail sending via various services supported.

Select Email Sending Service

2. Choose service provider via Add New Service -> Select Service


It supports various services like Gmail, Yahoo and etc. It also have settings to configure custom SMTP server  with this online solution.
Permit EmailJS To Access Mail Account

3. Design mail template by Email Templates -> Create New Template -> Select Template


There are various built-in templates in the EmailJS dashboard. I selected the “Contact Us” template for this example.

Template edit interface has the option to change the design and the content. It allows to add dynamic variables as part of the mail content.

When calling the EmailJS service, the request will have values to replace this variables. This feature will help to send a personalized email content.

Copy the Template ID once created an email template.

Design EmailJS Template

4. Get EmailJS API Public Key


Added Service ID, Template ID the EmailJS Public Key  is also need to initiate the library class from the frontend React App.

Navigate via Account using the left menu to open the API keys section. Copy Public Key from the EmailJS dashboard.

Get EmailJS Account Public Key

Initiate EmailJS library to React App


Create a React app and install the EmailJS library to it using this command.

npm install emailjs-com

This example code contains this library installed. So, just run npm install to bring the dependancies into your node_modules.

Then, import the emailjs-com to the React JSX and initiate the EmailJS service as shown below. This script shows how the emailjs instance is used in the form handle submit.

import emailjs from "emailjs-com"; const handleSubmit = (e) => { e.preventDefault(); const SERVICE_ID = "Your Serivce ID"; const TEMPLATE_ID = "Your Template ID"; const PUBLIC_KEY = "EmailJS API Public key here"; emailjs .send(SERVICE_ID, TEMPLATE_ID, formData, PUBLIC_KEY) .then(() => { toast.success("Email sent successfully!", { position: "top-center" }); setFormData({ name: "", email: "", message: "" }); }) .catch(() => { toast.error("Failed to send email. Please try again.", { position: "top-center", }); }); };

Example React form to send email


This example provides component for the email sending form fields. The fields UI code is moved to a separate file and made as a component. It is imported into the parent container in the EmailForm component.

It renders Name, Email and Message fields. Each fields is validated with a handleChange hook.

react send mail form

src/components/EmailFormFields.jsx

const EmailFormFields = ({ formData, handleChange }) => {
return ( <> <div className="form-group"> <label className="form-label">Name</label> <input type="text" name="name" value={formData.name} on‌Change={handleChange} className="form-input" required /> </div> <div className="form-group"> <label className="form-label">Email</label> <input type="email" name="email" value={formData.email} on‌Change={handleChange} className="form-input" required /> </div> <div className="form-group"> <label className="form-label">Message</label> <textarea name="message" value={formData.message} on‌Change={handleChange} className="form-input" rows="6" required ></textarea> </div> </>
);
};
export default EmailFormFields;

React JSX to load EmailJS and EmailFormFields Component


This JSX defines the handleChange and handleSubmit hooks for validation and mail sending respectively.

The form container includes the <EmailFormFields />, Submit button and a <ToastContainer />.

After sending email via emailjs, the handleSubmit action resets the form and make it ready for the next submit.

When submitting the form, the handleSubmit function sends the formData with the API keys and IDs. Configure your EmailJS keys and IDs to this React script to make this example to send email.

src/components/EmailForm.jsx

import { useState } from "react";
import emailjs from "emailjs-com";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import "../../public/assets/css/phppot-style.css";
import EmailFormFields from "./EmailFormFields"; const EmailForm = () => { const [formData, setFormData] = useState({ name: "", email: "", message: "", }); const handleChange = (e) => { const { name, value } = e.target; setFormData((prev) => ({ ...prev, [name]: value })); }; const handleSubmit = (e) => { e.preventDefault(); const SERVICE_ID = "Your Serivce ID"; const TEMPLATE_ID = "Your Template ID"; const PUBLIC_KEY = "EmailJS API Public key here"; emailjs .send(SERVICE_ID, TEMPLATE_ID, formData, PUBLIC_KEY) .then(() => { toast.success("Email sent successfully!", { position: "top-center" }); setFormData({ name: "", email: "", message: "" }); }) .catch(() => { toast.error("Failed to send email. Please try again.", { position: "top-center", }); }); }; return ( <div className="form-wrapper"> <h2 className="form-title">Contact Us</h2> <form on‌Submit={handleSubmit} className="payment-form"> <EmailFormFields formData={formData} handleChange={handleChange} /> <button type="submit" className="submit-btn"> Send </button> </form> <ToastContainer /> </div> );
};
export default EmailForm;

Note: Form data is in an associate array format, where the array keys matches the email template variables. For example, if the email template body in the EmailJS dashboard contains Hi {{name}}, then the form data will have the key-value as name: submitted-name to replace the variable.

The receive email signature and the mail body design will be as configured in the EmailJS dashboard. The following diagram shows the received email output.

React Received Web Mail

Conclusion


Thus, we have created a frontend in React for sending email without any backend set up. I hope, you find EmailJS very simple to integrate into an application. And its registration process is very simple. And, the features to customize the email body is very useful to have a thematic email template for different applications.

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top



https://www.sickgaming.net/blog/2025/11/...-required/

Print this item

  [Tut] Best Free Books for Distributed Systems PhD Students (Must Read!)
Posted by: xSicKxBot - 12-07-2025, 06:46 AM - Forum: Python - No Replies

[Tut] Best Free Books for Distributed Systems PhD Students (Must Read!)

Distributed systems form the backbone of modern large-scale computing, from cloud platforms to distributed databases and large clusters.

As a PhD student, you need resources that go beyond the basics, combining strong theoretical foundations with practical insights. And ideally, they should be freely accessible.

The following five books are all legally available online at no cost and are well-suited to accompany you through graduate-level research in distributed systems.

Distributed Systems (4th Edition) — Maarten van Steen & Andrew S. Tanenbaum



This modern classic offers a broad and rigorous introduction to distributed systems, covering architectures, communication, naming, coordination, replication, fault tolerance, and security. The 4th edition updates many examples to reflect today’s large-scale systems and is widely used in advanced undergraduate and graduate courses. A personalized digital copy is available for free from the authors’ website.

Access the free digital edition

Distributed Systems for Fun and Profit — Mikito Takada



Short, opinionated, and surprisingly deep, this book is great when you want to quickly grasp the core concepts behind real-world distributed systems. It walks through consistency models, time and ordering, replication strategies, and the design of systems like Dynamo and Bigtable, always with an eye toward what matters in practice. Its informal style makes it perfect as a first pass or as a companion to more formal texts.

Read the book online for free

The Datacenter as a Computer: Designing Warehouse-Scale Machines (3rd Edition) — Luiz André Barroso, Urs Hölzle, Parthasarathy Ranganathan



If you’re doing a PhD, you’ll likely care about how your algorithms and systems behave at data-center scale. This open-access book treats an entire datacenter as a single “warehouse-scale computer” and explains how to design, operate, and optimize such systems. It’s particularly valuable for understanding the hardware, energy, and reliability constraints behind large distributed services such as those run by major cloud providers.

Download the open-access book (PDF and more)

Operating Systems: Three Easy Pieces — Remzi H. Arpaci-Dusseau & Andrea C. Arpaci-Dusseau



While technically an operating-systems book, OSTEP is essential background for anyone doing serious work in distributed systems. Its deep treatment of concurrency, synchronization, and persistence provides the building blocks that distributed algorithms and storage systems rely on. The clear structure, numerous exercises, and freely available PDFs make it ideal for self-study alongside more specialized distributed-systems material.

Access the free online textbook and PDFs

Distributed Algorithms — Jukka Suomela



These lecture notes form a full-fledged graduate-level textbook on distributed algorithms, focusing on rigorous models and proofs. Topics include locality, symmetry breaking, graph problems, and complexity in distributed settings, making it an excellent bridge between theory and the systems-oriented books above. If your PhD work touches consensus, graph algorithms on networks, or lower bounds in distributed computing, this text is a highly relevant free resource.

Download the lecture-notes textbook as PDF


Also check out my other free book articles:

? 42 Best Free AI Books (HTML/PDF)



https://www.sickgaming.net/blog/2025/11/...must-read/

Print this item

  [Tut] React JWT Authentication Tutorial with PHP Backend (Login, Register & Protecte
Posted by: xSicKxBot - 12-07-2025, 06:46 AM - Forum: PHP Development - No Replies

[Tut] React JWT Authentication Tutorial with PHP Backend (Login, Register & Protecte

by Vincy. Last modified on November 28th, 2025.

The JWT authentication is a secure way of implementing a web login process without session management. This tutorial is for implementing React JWT authentication with PHP. It has the following steps to understand the process easily.

Additionally, this example code provides a user registration code to create new user to the database. With the registration and login code you are getting a base for your websites authentication module from this tutorial.

  1. React login form submits the registered username and password.
  2. PHP backend script validates the login details with the database.
  3. PHP login success case generates JWT signed encoded user profile data.
  4. React frontend receives the JWT token and stores to localStorage.
  5. React validates the existence of the token with the ProtectedRoutes component.
  6. If the ProtectedRoutes failed to find the JWT token, it denies the access.

React Jwt Authentication Php Backend Login Register

React User Registration


This registration code helps to create data for your login process. Also, with registration this authentication example will be a more complete version to deploy in your application.

This example has a registration form with very few fields. React builds the formData state when the user enters the data. On submit, it passes the entered data to the PHP page register-action.php. It stores the user login name, email and the password to the database.

In the below JSX script, the formData, success/error state variables are managed. The handleSubmit hook handles the client-side form validation. This hook posts the data to the server once the validation returns true.

Part of RegisterForm.jsx with React states and hooks

import axios from "axios";
import { useNavigate } from "react-router-dom";
import SERVER_SIDE_API_ROOT from "../config";
import "../styles/style.css";
const RegisterForm = () => { const [formData, setFormData] = useState({ username: "", email: "", password: "", confirmPassword: "", }); const [errorMessage, setErrorMessage] = useState(""); const [successMessage, setSuccessMessage] = useState(""); const navigate = useNavigate(); const handleSubmit = async (e) => { e.preventDefault(); const { username, email, password, confirmPassword } = formData; if (!username || !email || !password || !confirmPassword) { setErrorMessage("Please fill in all fields"); setSuccessMessage(""); return; } const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(email)) { setErrorMessage("Please enter a valid email address"); return; } if (password.length < 6) { setErrorMessage("Password must be at least 6 characters"); return; } if (password !== confirmPassword) { setErrorMessage("Passwords do not match"); setSuccessMessage(""); return; } try { const res = await axios.post( `${SERVER_SIDE_API_ROOT}/registration-action.php`, { username, email, password }, { headers: { "Content-Type": "application/json" } } ); console.log("Server response:", res.data); if (res.data.status === "success") { setSuccessMessage(res.data.message); setErrorMessage(""); setFormData({ username: "", email: "", password: "", confirmPassword: "", }); setTimeout(() => { navigate("/login"); }, 2000); } else { setErrorMessage(res.data.message || "Registration failed"); setSuccessMessage(""); } } catch (err) { console.error("Axios Error:", err); setErrorMessage("Server error or CORS issue"); setSuccessMessage(""); }
};

react jwt registration

Returning Form UI code with RegisterForm.jsx

<div className="admin-wrapper"> <div className="card-container" style={{ maxWidth: "400px", margin: "95px auto" }}> <h2>User Registration</h2> <form on‌Submit={handleSubmit}> <div> <label>Username:</label> <input value={formData.username} on‌Change={(e) => setFormData({ ...formData, username: e.target.value }) }/> </div> <div> <label>Email:</label> <input type="email" value={formData.email} on‌Change={(e) => setFormData({ ...formData, email: e.target.value }) } /> </div> <div> <label>Password:</label> <input type="password" value={formData.password} on‌Change={(e) => setFormData({ ...formData, password: e.target.value }) } /> </div> <div> <label>Confirm Password:</label> <input type="password" value={formData.confirmPassword} on‌Change={(e) => setFormData({ ...formData, confirmPassword: e.target.value, }) }/> </div> {errorMessage && ( <div className="alert alert-danger" role="alert"> {errorMessage} </div> )} {successMessage && ( <div className="alert alert-success" role="alert"> {successMessage} </div> )} <button type="submit">Register</button> <p style={{ textAlign: "center", marginTop: "10px" }}> Already have an account?{" "} <a href="/login" style={{ color: "#232323", fontWeight: "600",textDecoration: "none" }}> Login here </a> </p> </form> </div> </div>
);
};
export default RegisterForm;

PHP backend handles the registration request and stores the entered password in an encrypted form. It validates the user email uniqueness. If the entered email is already in the database, then this code rejects the user’s insertion.

react-jwt-login-register-api/registration-action.php

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json"); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
include "db.php";
$input = file_get_contents("php://input");
$data = json_decode($input);
if ( !isset($data->username) || !isset($data->email) || !isset($data->password)
) { echo json_encode(["status" => "error", "message" => "Invalid input"]); exit;
}
$username = mysqli_real_escape_string($conn, $data->username);
$email = mysqli_real_escape_string($conn, $data->email);
$password = password_hash($data->password, PASSWORD_BCRYPT);
$check = $conn->query("SELECT * FROM users WHERE email='$email'");
if ($check->num_rows > 0) { echo json_encode(["status" => "error", "message" => "Email already exists"]); exit;
}
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
if ($conn->query($sql) === TRUE) { echo json_encode(["status" => "success", "message" => "Registration successful"]);
} else { echo json_encode(["status" => "error", "message" => $conn->error]);
}
?>

React login JWT authentication


If the user submits the correct username and password, the client receives success response from the server. The response will contain a JWT signed user profile data array.

In the client-side, the jwt-decode is used to decode the JWT response. The jwt-decode is the JavaScript library which can read and decode the JWT encoded string.

Run the following command to install this library into the application repository.

npm install jwt-decode [OR] yarn add jwt-decode

react jwt login

In the below script, if the response status is success it sets the JWT authentication token to a JavaScript localStorage. Then, it redirects to the dashboard. The dashboard is a protected page that can be accessed if a user is JWT-authenticated.

src/components/LoginForm.jsx

import React, { useState } from "react";
import { Link } from "react-router-dom";
import SERVER_SIDE_API_ROOT from "../config";
import "../styles/style.css";
import axios from "axios"; const LoginForm = () => { const [formData, setFormData] = useState({ username: "", password: "", }); const [errorMessage, setErrorMessage] = useState(""); const handleLogin = (e) => { e.preventDefault(); const { username, password } = formData; if (!username || !password) { setErrorMessage("Please enter both username and password"); return; } axios.post(`${SERVER_SIDE_API_ROOT}/login-action.php`, { username, password, }) .then((res) => { if (res.data.status === "success") { localStorage.setItem("token", res.data.token); setErrorMessage(""); setTimeout(() => { window.location.href = "/dashboard"; }, 1000); } else { setErrorMessage(res.data.message); } }) .catch((err) => { setErrorMessage("Server error: " + err.message); });
};
return (
<div className="admin-wrapper"> <div className="card-container" style={{ maxWidth: "400px", margin: "154px auto" }}> <h2>Login</h2> <form on‌Submit={handleLogin}> <div> <label>Username:</label> <input value={formData.username} on‌Change={(e) => setFormData({ ...formData, username: e.target.value })} /> </div> <div> <label>Password:</label> <input type="password" value={formData.password} on‌Change={(e) => setFormData({ ...formData, password: e.target.value }) } /> </div> {errorMessage && ( <div className="alert alert-danger" role="alert"> {errorMessage} </div> )} <button type="submit">Login</button> <p style={{ textAlign: "center", marginTop: "10px" }}> Don’t have an account?{" "} <Link to="/registerform" style={{ color: "#232323", fontWeight: "600", textDecoration: "none" }}> Register here </Link> </p> </form> </div>
</div>
);
};
export default LoginForm;

In PHP the firebase/php-jwt library is installed by using this composer command. Once the logged-in details matched, this library is used to generate the JWT token with the profile array.

composer require firebase/php-jwt

react-jwt-login-register-api/login-action.php

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json"); include "db.php";
require 'vendor/autoload.php'; use Firebase\JWT\JWT;
use Firebase\JWT\Key; $secret_key = "MY_SECRET_KEY_12345"; if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { http_response_code(200); exit;
}
$data = json_decode(file_get_contents("php://input"));
if (!isset($data->username) || !isset($data->password)) { echo json_encode(["status" => "error", "message" => "Missing credentials"]); exit;
}
$username = $conn->real_escape_string($data->username);
$password = $data->password;
$result = $conn->query("SELECT * FROM users WHERE username = '$username' LIMIT 1");
if ($result->num_rows === 0) { echo json_encode(["status" => "error", "message" => "Invalid Username or Password"]); exit;
}
$user = $result->fetch_assoc();
if (!password_verify($password, $user['password'])) { echo json_encode(["status" => "error", "message" => "Invalid password"]); exit;
}
$payload = [ "iss" => "http://localhost", "aud" => "http://localhost", "iat" => time(), "exp" => time() + (60 * 60), "user" => [ "id" => $user['id'], "username" => $user['username'], "email" => $user['email'] ]
];
$jwt = JWT::encode($payload, $secret_key, 'HS256');
echo json_encode([ "status" => "success", "message" => "Login successful", "token" => $jwt
]);
?>

Protected Route Component that validates JWT token to permit


This component validates if the localStorage has the JWT token. If not, then it will stop the user from accessing a requested page. Instead, it redirects to the login page.

src/components/ProtectedRoute.js

import { Navigate } from "react-router-dom"; const ProtectedRoute = ({ children }) => { const token = localStorage.getItem("token"); if (!token) { return <Navigate to="/login" replace />; } return children;
}; export default ProtectedRoute;

Dashboard with profile information


The React main App component imports the ProtectedRoutes to bring the validation process at the top layer. This ProtectedRoutes wrapper around the Dashboard will help to permit only a JWT-authenticated user to the dashboard.

This React dashboard script gets the user details from the decoded JWT token. Then, those details are rendered to the UI as shown below.

A simple header is created for this dashboard view with a logout option. On clicking logout, it clears the localStorage and redirects to the login page.

react jwt dashboard

src/pages/Dashboard.jsx

import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { jwtDecode } from "jwt-decode";
import "../styles/style.css"; const Dashboard = () => { const [user, setUser] = useState(null); const navigate = useNavigate(); useEffect(() => { const token = localStorage.getItem("token"); if (!token) { navigate("/login"); return; } try { const decoded = jwtDecode(token); setUser(decoded.user); } catch (error) { console.error("Invalid token:", error); localStorage.removeItem("token"); navigate("/login"); } }, [navigate]); if (!user) return <p>Loading...</p>; const handleLogout = () => { localStorage.removeItem("token"); navigate("/login"); }; return ( <div className="dashboard-wrapper"> <nav className="navbar"> <div className="navbar-left"> <h2>Dashboard</h2> </div> <div className="navbar-right"> <button className="logout-btn" on‌Click={handleLogout}> <img src="./logout.svg" alt="Logout" className="logout-icon" /> </button> </div> </nav> <div className="card"> <img src="/profile.jpg" alt="" className="profile-pic" /> <h2>Welcome, {user.username}</h2> <p> <strong>Email:</strong> {user.email} </p> </div> </div> );
};
export default Dashboard;

conclusion


With this login authentication base, you can have a good start to create a React JWT login. The user registration involves PHP and MySQL connection to generate backend data for this login. It can be enhanced by adding server-side JWT validation to improve the security. The concept of securing application pages with protected routes helps to reuse the wrapper for more components.

References:

  1. About JWT (JSON Web Token)
  2. PHP JWT backend library to encode decode JWT token
  3. Client side JWT decoding library

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top



https://www.sickgaming.net/blog/2025/10/...ed-routes/

Print this item

  News - Fallout Creator Rejoins Obsidian, Has A New Squirrel Friend
Posted by: xSicKxBot - 12-07-2025, 05:14 AM - Forum: Lounge - No Replies

News - Fallout Creator Rejoins Obsidian, Has A New Squirrel Friend

Fallout creator Tim Cain has returned to Obsidian, but what is he working on? He's not allowed to say, and says you shouldn't even try to guess. Cain also shared an update about his personal life and a new friendship with a squirrel.

In a YouTube video, Cain said he recently relocated from Seattle to southern California, and one of the first things that happened was a squirrel ran up to him with no fear. "She just sat there and looked at me, and I shrugged and I'm like, 'What do you want from me? I don't know you.'" Cain fed the critter some walnuts and continues to feed the creature every day when he leaves and comes back home.

This is how Cain started the video, before getting into his return to Obsidian. He said he's now back at the studio, in-person and full-time. While he has returned to Obsidian, you'll also see his name appear in the credits of an upcoming unspecified game that he did contract work for before coming back to Obsidian, he said.

Continue Reading at GameSpot

https://www.gamespot.com/articles/fallou...01-10abi2f

Print this item

  [Tut] Best Ways to Remove Unicode from List in Python
Posted by: xSicKxBot - 12-06-2025, 01:55 PM - Forum: Python - No Replies

[Tut] Best Ways to Remove Unicode from List in Python

5/5 – (1 vote)

When working with lists that contain Unicode strings, you may encounter characters that make it difficult to process or manipulate the data or handle internationalized content or content with emojis ?. In this article, we will explore the best ways to remove Unicode characters from a list using Python.

You’ll learn several strategies for handling Unicode characters in your lists, ranging from simple encoding techniques to more advanced methods using list comprehensions and regular expressions.

Understanding Unicode and Lists in Python


Combining Unicode strings and lists in Python is common when handling different data types. You might encounter situations where you need to remove Unicode characters from a list, for instance, when cleaning or normalizing textual data.

? Unicode is a universal character encoding standard that represents text in almost every writing system used today. It assigns a unique identifier to each character, enabling the seamless exchange and manipulation of text across various platforms and languages. In Python 2, Unicode strings are represented with the u prefix, like u'Hello, World!'. However, in Python 3, all strings are Unicode by default, making the u prefix unnecessary.

⛓ Lists are a built-in Python data structure used to store and manipulate collections of items. They are mutable, ordered, and can contain elements of different types, including Unicode strings.

For example:

my_list = ['Hello', u'世界', 42]

While working with Unicode and lists in Python, you may discover challenges related to encoding and decoding strings, especially when transitioning between Python 2 and Python 3. Several methods can help you overcome these challenges, such as encode(), decode(), and using various libraries.

Method 1: ord() for Unicode Character Identification


One common method to identify Unicode characters is by using the isalnum() function. This built-in Python function checks if all characters in a string are alphanumeric (letters and numbers) and returns True if that’s the case, otherwise False. When working with a list, you can simply iterate through each string item and use isalnum() to determine if any Unicode characters are present.

The isalnum() function in Python checks whether all the characters in a text are alphanumeric (i.e., either letters or numbers) and does not specifically identify Unicode characters. Unicode characters can also be alphanumeric, so isalnum() would return True for many Unicode characters.

To identify or work with Unicode characters in Python, you might use the ord() function to get the Unicode code of a character, or \u followed by the Unicode code to represent a character. Here’s a brief example:


# Using \u to represent a Unicode character
unicode_char = '\u03B1' # This represents the Greek letter alpha (α) # Using ord() to get the Unicode code of a character
unicode_code = ord('α') print(f"The Unicode character for code 03B1 is: {unicode_char}")
print(f"The Unicode code for character α is: {unicode_code}")

In this example:

  • \u03B1 is used to represent the Greek letter alpha (α) using its Unicode code.
  • ord('α') returns the Unicode code for the Greek letter alpha, which is 945.

If you want to identify whether a string contains non-ASCII characters (which might be what you’re interested in when you talk about identifying Unicode characters), you might use something like the following code:

def contains_non_ascii(s): return any(ord(char) >= 128 for char in s) # Example usage:
s = "Hello α"
print(contains_non_ascii(s)) # Output: True print(contains_non_ascii('Hello World')) # Output: False

In this function, contains_non_ascii(s), it checks each character in the string s to see if it has a Unicode code greater than or equal to 128 (i.e., it is not an ASCII character). If any such character is found, it returns True; otherwise, it returns False.

Method 2: Regex for Unicode Identification


Using regular expressions (regex) is a powerful way to identify Unicode characters in a string. Python’s re module can be utilized to create patterns that can match Unicode characters. Below is an example method that uses a regular expression to identify whether a string contains any Unicode characters:


import re def contains_unicode(input_string): """ This function checks if the input string contains any Unicode characters. Parameters: input_string (str): The string to check for Unicode characters. Returns: bool: True if Unicode characters are found, False otherwise. """ # The pattern \u0080-\uFFFF matches any Unicode character with a code point # from 128 to 65535, which includes characters from various scripts # (Latin Extended, Greek, Cyrillic, etc.) and various symbols. unicode_pattern = re.compile(r'[\u0080-\uFFFF]') # Search for the pattern in the input string if re.search(unicode_pattern, input_string): return True else: return False # Example usage:
s1 = "Hello, World!"
s2 = "Hello, 世界!" print(contains_unicode(s1)) # Output: False
print(contains_unicode(s2)) # Output: True

Explanation:

  • [\u0080-\uFFFF]: This pattern matches any character with a Unicode code point from U+0080 to U+FFFF, which includes various non-ASCII characters.
  • re.search(unicode_pattern, input_string): This function searches the input string for the defined Unicode pattern.
  • If the pattern is found in the string, the function returns True; otherwise, it returns False.

This method will help you identify strings containing Unicode characters from various scripts and symbols. This pattern does not match ASCII characters (code points U+0000 to U+007F) or non-BMP characters (code points above U+FFFF).

If you want to learn about Python’s search() function in regular expressions, check out my tutorial and tutorial video:

YouTube Video

Method 3: Encoding and Decoding for Unicode Removal


When dealing with Python lists containing Unicode characters, you might find it necessary to remove them. One effective method to achieve this is by using the built-in string encoding and decoding functions. This section will guide you through the process of Unicode removal in lists by employing the encode() and decode() methods.

First, you will need to encode the Unicode string into the ASCII format. It is essential because the ASCII encoding only supports ASCII characters, and any Unicode characters that are outside the ASCII range will be automatically removed. For this, you can utilize the encode() function with its parameters set to the ASCII encoding option and error handling set to 'ignore'.

For example:

string_unicode = "? ?? ???????!"
string_ascii = string_unicode.encode('ascii', 'ignore')

After encoding the string to ASCII, it is time to decode it back to a UTF-8 format. This step is essential to ensure the list items retain their original text data and stay readable. You can use the decode() function to achieve this conversion. Here’s an example:

string_utf8 = string_ascii.decode('utf-8')

Now that you have successfully removed the Unicode characters, your Python list will only contain ASCII characters, making it easier to process further. Let’s take a look at a practical example with a list of strings.

list_unicode = ["? ?? ???????!", "This is an ASCII string", "???? ?? ???????"]
list_ascii = [item.encode('ascii', 'ignore').decode('utf-8') for item in list_unicode] print(list_unicode)
# ['? ?? ???????!', 'This is an ASCII string', '???? ?? ???????'] print(list_ascii)
# [' !', 'This is an ASCII string', ' ']

In this example, the list_unicode variable comprises three different strings, two with Unicode characters and one with only ASCII characters. By employing a list comprehension, you can apply the encoding and decoding process to each string in the list.

? Recommended: Python List Comprehension – The Ultimate Guide

Remember always to be careful when working with Unicode texts. If the string with Unicode characters contains crucial information or an essential part of the data you are processing, you should consider keeping the Unicode characters and using proper Unicode-compatible solutions.

Method 4: The Replace Function for Unicode Removal


When working with lists in Python, it is common to come across Unicode characters that need to be removed or replaced. One technique to achieve this is by using Python’s replace() function.

The replace() function is a built-in method in Python strings, which allows you to replace occurrences of a substring within a given string. To remove specific Unicode characters from a list, you can first convert the list elements into strings, then use the replace() function to handle the specific Unicode characters.

Here’s a simple example:

original_list = ["Róisín", "Björk", "Héctor"]
new_list = [] for item in original_list: new_item = item.replace("ó", "o").replace("ö", "o").replace("é", "e") new_list.append(new_item) print(new_list) # ['Roisin', 'Bjork', 'Hector']

When dealing with a larger set of Unicode characters, you can use a dictionary to map each character to be replaced with its replacement. For example:

unicode_replacements = { "ó": "o", "ö": "o", "é": "e", # Add more replacements as needed.
} original_list = ["Róisín", "Björk", "Héctor"]
new_list = [] for item in original_list: for key, value in unicode_replacements.items(): item = item.replace(key, value) new_list.append(item) print(new_list) # ['Roisin', 'Bjork', 'Hector']

Of course, this is only useful if you have specific Unicode characters to remove. Otherwise, use the previous Method 3.

Method 5: Regex Substituion for Replacing Non-ASCII Characters


When working with text data in Python, non-ASCII characters can often cause issues, especially when parsing or processing data. To maintain a clean and uniform text format, you might need to deal with these characters and remove or replace them as necessary.

One common technique is to use list comprehension coupled with a character encoding method such as .encode('ascii', 'ignore'). You can loop through the items in your list, encode them to ASCII, and ignore any non-ASCII characters during the encoding process. Here’s a simple example:

data_list = ["? ?? ???????!", "Hello, World!", "你好!"]
clean_data_list = [item.encode("ascii", "ignore").decode("ascii") for item in data_list]
print(clean_data_list)
# Output: [' m mn!', 'Hello, World!', '']

In this example, you’ll notice that non-ASCII characters are removed from the text, leaving the ASCII characters intact. This method is both clear and easy to implement, which makes it a reliable choice for most situations.

Another approach is to use regular expressions to search for and remove all non-ASCII characters. The Python re module provides powerful pattern matching capabilities, making it an excellent tool for this purpose. Here’s an example that shows how you can use the re module to remove non-ASCII characters from a list:

import re data_list = ["? ?? ???????!", "Hello, World!", "你好!"]
ascii_only_pattern = re.compile(r"[^\x00-\x7F]")
clean_data_list = [re.sub(ascii_only_pattern, "", item) for item in data_list]
print(clean_data_list) # Output: [' !', 'Hello, World!', '']

In this example, we define a regular expression pattern that matches any character outside the ASCII range ([^\x00-\x7F]). We then use the re.sub() function to replace any matching characters with an empty string.

Frequently Asked Questions


How can I efficiently replace Unicode characters with ASCII in Python?


To efficiently replace Unicode characters with ASCII in Python, you can use the unicodedata library. This library provides the normalize() function which can convert Unicode strings to their closest ASCII equivalent. For example:

import unicodedata def unicode_to_ascii(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category© != 'Mn')

This function will replace Unicode characters with their ASCII equivalents, making your Python list easier to work with.

What are the best methods to remove Unicode characters in Pandas?


Pandas has a built-in method that helps you remove Unicode characters in a DataFrame. You can use the applymap() function in conjunction with the lambda function to remove any non-ASCII character from your DataFrame. For example:

import pandas as pd data = {'col1': [u'こんにちは', 'Pandas', 'DataFrames']}
df = pd.DataFrame(data) df = df.applymap(lambda x: x.encode('ascii', 'ignore').decode('ascii'))

This will remove all non-ASCII characters from the DataFrame, making it easier to process and analyze.

How do I get rid of all non-English characters in a Python list?


To remove all non-English characters in a Python list, you can use list comprehension and the isalnum() function from the str class. For example:

data = [u'こんにちは', u'Hello', u'안녕하세요'] result = [''.join(c for c in s if c.isalnum() and ord© &#x3C; 128) for s in data]

This approach filters out any character that isn’t alphanumeric or has an ASCII value greater than 127.

What is the most effective way to eliminate Unicode characters from an SQL string?


To eliminate Unicode characters from an SQL string, you should first clean the data in your programming language (e.g., Python) before inserting it into the SQL database. In Python, you can use the re library to remove Unicode characters:

import re def clean_sql_string(s): return re.sub(r'[^\x00-\x7F]+', '', s)

This function will remove any non-ASCII characters from the string, ensuring that your SQL query is free of Unicode characters.

How can I detect and handle Unicode characters in a Python script?


To detect and handle Unicode characters in a Python script, you can use the ord() function to check if a character’s Unicode code point is outside the ASCII range. This allows you to filter out any Unicode characters in a string. For example:

def is_ascii(s): return all(ord© < 128 for c in s)

You can then handle the detected Unicode characters accordingly, such as using replace() to substitute them with appropriate ASCII characters or removing them entirely.

What techniques can be employed to remove non-UTF-8 characters from a text file using Python?


To remove non-UTF-8 characters from a text file using Python, you can use the following method:

  1. Open the file in binary mode.
  2. Decode the file’s content with the ‘UTF-8’ encoding, using the ‘ignore’ or ‘replace’ error handling mode.
  3. Write the decoded content back to the file.
with open('file.txt', 'rb') as file: content = file.read() cleaned_content = content.decode('utf-8', 'ignore') with open('cleaned_file.txt', 'w', encoding='utf-8') as file: file.write(cleaned_content)

This will create a new text file without non-UTF-8 characters, making your data more accessible and usable.

Footnotes


  1. 7 Best Ways to Remove Unicode Characters in Python
  2. What is the simplest way to remove unicode ‘u’ from a list

The post Best Ways to Remove Unicode from List in Python appeared first on Be on the Right Side of Change.



https://www.sickgaming.net/blog/2023/10/...in-python/

Print this item

  [Tut] React + Node + MySQL CRUD App Tutorial (Full-Stack API Integration)
Posted by: xSicKxBot - 12-06-2025, 01:55 PM - Forum: PHP Development - No Replies

[Tut] React + Node + MySQL CRUD App Tutorial (Full-Stack API Integration)

by Vincy. Last modified on November 6th, 2025.

This tutorial has a React NodeJS example for building a full-stack CRUD application. It gives easy guidelines to design the frontend and backend. The frontend React connects the NodeJS API controllers to interact for creating, reading, updating, and deleting. This will provide persistent storage with a MySQL database connected via API DAOs.

React Node Mysql Crud Full Stack Tutorial

Add form design and user creation with NodeJS and MySQL


The user-create form contains only two fields to simplify the example. So, the React frontend assets manages states and props to carry these inputs’ data to post.

The addUser() props triggers the add action request to post the form data to the server.

It executes the insert query on clicking the ‘Add User’ button. The response will have the auto-generated key created on successful insert action of the CRUD functionality.

src/components/form/AddUserForm.jsx

import { useState } from 'react'
const AddUserForm = props => { const initialFormState = { id: null, name: '', username: '' } const [ user, setUser ] = useState(initialFormState) const handleInputChange = event => { const { name, value } = event.target setUser({ ...user, [name]: value }) }
return ( <form on‌Submit={event => { event.preventDefault() if (!user.name || !user.username) return props.addUser(user) setUser(initialFormState) }}> <label>Name</label> <input type="text" name="name" value={user.name} on‌Change={handleInputChange} /> <label>Username</label> <input type="text" name="username" value={user.username} on‌Change={handleInputChange} /> <div className="action-buttons"> <button type="submit">Add User</button> </div> </form>
)
}
export default AddUserForm

part of userControllers.js

export const addUser = (req, res) => { const { name, username } = req.body; db.query("INSERT INTO users (name, username) VALUES (?, ?)", [name, username], (err, result) => { if (err) return res.status(500).json({ error: err.message }); res.json({ id: result.insertId, name, username }); });
};

react crud add user

Displaying user data rows with edit and delete action controls


The UserTable component displays the data table dynamically from the MySQL database. The prop.users tree map is used to form these rows to the UI.

Each row contains edit and delete controls that are bound to editRow and deleteUser functions respectively.

src/components/table/UserTable.jsx

import React from 'react'
const UserTable = props => ( <table> <thead> <tr> <th>Name</th> <th>Username</th> <th>Actions</th> </tr> </thead> <tbody> {props.users.length > 0 ? ( props.users.map(user => ( <tr key={user.id}> <td>{user.name}</td> <td>{user.username}</td> <td> <button on‌Click={() => { props.editRow(user) }} className="button muted-button" > Edit </button> <button on‌Click={() => props.deleteUser(user.id)} className="button muted-button" > Delete </button> </td> </tr> )) ) : ( <tr> <td colSpan={3}>No users</td> </tr> )} </tbody> </table>
)
export default UserTable

In NodeJS the getUsers() module reads all users into an JSON response array as built below.

part of userControllers.js

export const getUsers = (req, res) => { db.query("SELECT * FROM users", (err, results) => { if (err) return res.status(500).json({ error: err.message }); res.json(results); });
};

Updating current user by ID using update API in NodeJS


The add and edit forms are exactly same except that this edit form populated the existing user data. The currentUser props contains the exiting user details read by id.

On clicking the ‘Edit’ button the user id is passed to send the read request with the id.

Once the enduser edits the detail and submit, it request the NodeJS API to perform the update operation of the CRUD module.

Both add and edit button clicks prevents the default submit and requests the API via network call.

The edit form is used to view or edit the user details. When clicking cancel the editing directive is set to false to switch to the view mode.

src/components/form/EditUserForm

import { useState, useEffect } from 'react'
const EditUserForm = props => { const [user, setUser] = useState(props.currentUser) useEffect( () => { setUser(props.currentUser) }, [props] ) const handleInputChange = event => { const { name, value } = event.target setUser({ ...user, [name]: value }) }
return ( <form on‌Submit={event => { event.preventDefault() props.updateUser(user.id, user) }} > <label>Name</label> <input type="text" name="name" value={user.name} on‌Change={handleInputChange} /> <label>Username</label> <input type="text" name="username" value={user.username} on‌Change={handleInputChange} /> <div className="action-buttons"> <button type="submit">Update User</button> <button on‌Click={() => props.setEditing(false)} className="button muted-button"> Cancel </button> </div> </form>
)
}
export default EditUserForm

In the NodeJS, the backend user controller has an exclusive handle to prepare the user update query.

It binds the request parameter to the update query to go with the update operation.

part of userControllers.js

export const updateUser = (req, res) => { const { id } = req.params; const { name, username } = req.body; db.query("UPDATE users SET name=?, username=? WHERE id=?", [name, username, id], (err) => { if (err) return res.status(500).json({ error: err.message }); res.json({ id, name, username }); });
};

react crud edit user

Deleting a user row via NodeJS controller


As like as an edit request, the delete action is also receives the user’s unique id in the request parameter.

The backend Node API receives the id and process the delete operation.

In the React frontend, it shows confirmation message in a toast box to avoid the mistakes.

part of userControllers.js

export const deleteUser = (req, res) => { const { id } = req.params; db.query("DELETE FROM users WHERE id=?", [id], (err) => { if (err) return res.status(500).json({ error: err.message }); res.json({ message: "User deleted" }); });
};

react crud delete user

How to run the React + NodeJS example?


Set up the MySQL database:

First find the /api/sql/users.sql file from the downloadable source code given in this React + NodeJS CRUD example.

Create a database and import that SQL script into that. Then Configure the database details to the db.js file in the NodeJS API root.
Start the backend NodeJS server:

Go to the NodeJS api path and start the server via npm. It will return the server running path http://localhost:5000/

In this example this backend api URL is configured with a specific constant for convenience. It avoid the overhead of changing in multiple places based on the environment.

cd /path/api npm install npm start node server.js

Start the frontend React dev:

Go to the app location path and start the dev server. This will start the dev server http://localhost:5173/

cd react-node-mysql-crud-full-stack-tutorial npm install npm run dev

Conclusion


This tutorial built a simple code for React + Node.js + MySQL CRUD. The code for designing frontend and connecting the NodeJS API together gives a full stack execution sample. I hope, you learned how to read and display dynamic data from backend to React components and also how to manipulate them. The server controller is with appropriate cases to handle the CRUD with MySQL to store, retrieve, update, and delete data. With this base, it is easy to add more features to this CRUD utility.

References:

  1. Installing MySQL client in NodeJS
  2. Secured database accessing with prepared statements.

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top



https://www.sickgaming.net/blog/2025/10/...tegration/

Print this item

  (Indie Deal) FREE Die Young, IG Anniversary, Star Forge Bundle
Posted by: xSicKxBot - 12-06-2025, 01:25 PM - Forum: Deals or Specials - No Replies

(Indie Deal) FREE Die Young, IG Anniversary, Star Forge Bundle

FREE Die Young
[freebies.indiegala.com]

IndieGala Anniversary
[www.indiegala.com]
Another year has passed & we once again celebrate our time together with a ton of surprises. Thank you for being part of the community & for being here with us now.

Star Forge Bundle | 6 Steam Games | 93% OFF
[www.indiegala.com]
Blast off into creativity, adventure, and puzzle-packed fun with the Star Forge Bundle — a curated collection of 6 vibrant indie games spanning action, strategy, arcade shooting, simulation, and dreamlike exploration. Featuring: Suika Shapes, Movie Cinema Simulator, Rob Riches, Star Hunter DX, Puzzle Forge Dungeon, Onirike

? Sale Highlights
? CRX Entertainment Sale[www.indiegala.com] – Exciting indie adventures and unique titles from this growing publisher.
? Nejcraft Interactive Sale[www.indiegala.com] – Dive into compelling indie worlds with great discounts.
?️ Private Division Sale[www.indiegala.com] – Premium strategy, RPG, and narrative titles from acclaimed developers.
⚔️ Topware Interactive Sale[www.indiegala.com] – A wide variety of genres, from tactical strategy to cinematic RPGs.
?️ HeroCraft PC Sale[www.indiegala.com] – Action, RPG, and adventure hits with big price cuts.
? Kasedo Games Sale[www.indiegala.com] – Indie gems, quirky experiments, and niche favorites now discounted.


https://steamcommunity.com/groups/indieg...6630615821

Print this item

 
Latest Threads
[Tut] ChatGPT 5.1 vs Gemi...
Last Post: xSicKxBot
10 hours ago
[Tut] How to Build a Reac...
Last Post: xSicKxBot
10 hours ago
[Tut] How to ship an AI-p...
Last Post: xSicKxBot
12-07-2025, 11:31 PM
[Tut] Send Email from Rea...
Last Post: xSicKxBot
12-07-2025, 11:31 PM
Black Ops (BO1, T5) DLC's...
Last Post: GulaabJaamun
12-07-2025, 09:15 AM
Black Ops (BO1, T5) DLC's...
Last Post: GulaabJaamun
12-07-2025, 09:13 AM
[Tut] Best Free Books for...
Last Post: xSicKxBot
12-07-2025, 06:46 AM
[Tut] React JWT Authentic...
Last Post: xSicKxBot
12-07-2025, 06:46 AM
News - Fallout Creator Re...
Last Post: xSicKxBot
12-07-2025, 05:14 AM
[Tut] Best Ways to Remove...
Last Post: xSicKxBot
12-06-2025, 01:55 PM

Forum software by © MyBB Theme © iAndrew 2016