in First Section code files in Second Section Steps perform to make this code run

Section:1

Users can sign up, log in, and view their "love affair" info on a protected page.

πŸ“¦ Tech Stack:

  • Frontend: React (Create React App or Vite)
  • Backend: PHP (API server)
  • Database: MySQL
  • Auth: Simple session or token-based login (we'll use sessions here for simplicity)

πŸ›  Project Overview

🧾 1. MySQL Database Schema

CREATE DATABASE love_app;
USE love_app;
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    password VARCHAR(255) NOT NULL,
    love_affair TEXT
);

πŸ“ Backend: PHP (e.g., in /backend folder)

πŸ“„ db.php

<?php
$pdo = new PDO("mysql:host=localhost;dbname=love_app", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
session_start();
?>

πŸ“„ signup.php

<?php
require 'db.php';
$data = json_decode(file_get_contents("php://input"), true);
$name = $data['name'] ?? '';
$pass = $data['password'] ?? '';
$love = $data['love'] ?? '';
if ($name && $pass) {
    $hashed = password_hash($pass, PASSWORD_BCRYPT);
    $stmt = $pdo->prepare("INSERT INTO users (name, password, love_affair) VALUES (?, ?, ?)");
    $stmt->execute([$name, $hashed, $love]);
    echo json_encode(["status" => "success"]);
} else {
    echo json_encode(["status" => "fail", "error" => "Missing fields"]);
}

πŸ“„ login.php

<?php
require 'db.php';
$data = json_decode(file_get_contents("php://input"), true);
$name = $data['name'] ?? '';
$pass = $data['password'] ?? '';
$stmt = $pdo->prepare("SELECT * FROM users WHERE name = ?");
$stmt->execute([$name]);
$user = $stmt->fetch();
if ($user && password_verify($pass, $user['password'])) {
    $_SESSION['user_id'] = $user['id'];
    echo json_encode(["status" => "success"]);
} else {
    echo json_encode(["status" => "fail", "error" => "Invalid credentials"]);
}
below file name πŸ“„ love.php
<?php
require 'db.php';
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthorized"]);
    exit;
}
$stmt = $pdo->prepare("SELECT love_affair FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();
echo json_encode(["love_affair" => $user['love_affair']]);

🌐 Frontend: React (/frontend)

Use fetch to talk to the PHP backend.

πŸ“„ Login.js

import { useState } from "react";
export default function Login({ onLogin }) {
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const login = async () => {
    const res = await fetch("http://localhost/backend/login.php", {
      method: "POST",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, password }),
    });
    const data = await res.json();
    if (data.status === "success") {
      onLogin();
    } else {
      alert("Login failed!");
    }
  };
  return (
    <div>
      <h2>Login</h2>
      <input placeholder="Name" onChange={(e) => setName(e.target.value)} />
      <input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
      <button onClick={login}>Login</button>
    </div>
  );
}
import { useState } from "react";
export default function Signup() {
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [love, setLove] = useState("");
  const signup = async () => {
    const res = await fetch("http://localhost/backend/signup.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, password, love }),
    });
    const data = await res.json();
    if (data.status === "success") {
      alert("Signed up!");
    } else {
      alert("Signup failed!");
    }
  };
  return (
    <div>
      <h2>Signup</h2>
      <input placeholder="Name" onChange={(e) => setName(e.target.value)} />
      <input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
      <input placeholder="Your Love Affair" onChange={(e) => setLove(e.target.value)} />
      <button onClick={signup}>Signup</button>
    </div>
  );
}

πŸ“„ LovePage.js

import { useEffect, useState } from "react";
export default function LovePage() {
  const [love, setLove] = useState("");
  useEffect(() => {
    fetch("http://localhost/backend/love.php", {
      credentials: "include"
    })
      .then(res => {
        if (!res.ok) throw new Error("Unauthorized");
        return res.json();
      })
      .then(data => setLove(data.love_affair))
      .catch(() => setLove("Not authorized"));
  }, []);
  return (
    <div>
      <h2>Your Love Affair ❀️</h2>
      <p>{love}</p>
    </div>
  );
}

SECTION : 2

πŸ’» Step-by-Step Setup on Your Laptop

πŸ—‚ 1. Project Folder Structure

Create a folder to hold your whole project:

mkdir love-affair-app
cd love-affair-app

Inside this, create two subfolders:

mkdir backend
mkdir frontend

πŸ›  2. Set Up MySQL Database

A. Open MySQL in terminal:

mysql -u root -p

Then paste this SQL to create your database and table:

CREATE DATABASE love_app;
USE love_app;
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    password VARCHAR(255) NOT NULL,
    love_affair TEXT
);

Then exit MySQL:

exit;

🐘 3. Set Up PHP Backend

A. Move to backend folder:

cd backend

B. Create files:

pase given code in this php files with this name 
db.php signup.php login.php love.php logout.php

Paste the PHP code I gave you into each corresponding file.

C. Start PHP server (from inside backend):

php -S localhost:8000

This runs the PHP backend on http://localhost:8000

βš›οΈ 4. Set Up React Frontend

A. Move to frontend folder:

cd ../frontend

B. Create React app (using Vite):

npm create vite@latest
  • Choose name: frontend
  • Select framework: React
  • Select variant: JavaScript

Then install dependencies:

cd frontend
npm install

C. Add Components:

Create 3 files in src/:

Paste the earlier React component code into each.

D. Update App.jsx:

import Signup from "./Signup";
import Login from "./Login";
import LovePage from "./LovePage";
import { useState } from "react";
function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  return (
    <div>
      <h1>Love Affair App πŸ’˜R</1>
      {!isLoggedIn ? (
        <>
          <Signup />
          <Login onLogin={() => setIsLoggedIn(true)} />
        </>
      ) : (
        <LovePage />
      )}
    </div>
  );
}
export default App;

πŸ”₯ 5. Run React Frontend

From inside the React app folder:

npm run dev

Vite will start your frontend on http://localhost:5173 (or similar).

🌐 6. Test the App

  • Open http://localhost:5173
  • Sign up with name, password, and a fun love affair message
  • Then log in
  • You'll see your secret love message appear