Creating a user registration system using PHP, MySQL, and React
Creating a user registration system using PHP, MySQL, and React involves several steps. Here’s a basic outline to get you started:
Initialize a React App:
npx create-react-app user-registration
cd user-registration
Create Registration Form:
// src/components/Register.js
import React, { useState } from 'react';
const Register = ( ) => {
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch('http://localhost:8000/register.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, email, password }),
});
const data = await response.json();
console.log(data);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={username} onChange={(e) => setUsername(e.target.value)} placeholder="Username" required />
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" required />
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" required />
<button type="submit">Register</button>
</form>
);
};
export default Register;
// register.php
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");
$data = json_decode(file_get_contents("php://input"));
$username = $data->username;
$email = $data->email;
$password = password_hash($data->password, PASSWORD_DEFAULT);
$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
if ($conn->query($sql) === TRUE) {
echo json_encode(["message" => "User registered successfully"]);
} else {
echo json_encode(["message" => "Error: " . $sql . "<br>" . $conn->error]);
}
$conn->close();
?>
CREATE DATABASE user_registration;
USE user_registration;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL
);
Run the React App:
npm start
Run the PHP Server:
php -S localhost:8000
This setup will allow you to capture user registration data from a React frontend, send it to a PHP backend, and store it in a MySQL database.