Jump to content

I need help my registration page, no data is getting inserted in the database


gula
Go to solution Solved by kicken,

Recommended Posts

I have created a the frontend fo the registration page in react and wrote backend in php and I have used mysql as my database 

This is my frontend code 

import React, { useState } from "react";

import "./css/Register.css";

import { Link } from "react-router-dom";

import axios from "axios";



function Register() {

  const [firstName, setFirstName] = useState("");

  const [lastName, setLastName] = useState("");

  const [email, setEmail] = useState("");

  const [mobileNumber, setMobileNumber] = useState("");

  const [password, setPassword] = useState("");

  const [confirmPassword, setConfirmPassword] = useState("");

  const [validationErrors, setValidationErrors] = useState({

    emailError: "",

    mobileNumberError: "",

    passwordMatchError: "",

  });



  const handleSubmit = (e) => {

    e.preventDefault();

    // Email validation using regular expression

    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    let newErrors = {

      emailError: "",

      mobileNumberError: "",

      passwordMatchError: "",

    };



    if (!emailPattern.test(email)) {

      newErrors.emailError = "Please enter a valid email address";

    }



    if (mobileNumber.length !== 10) {

      newErrors.mobileNumberError = "Please enter a valid mobile number";

    }



    if (password !== confirmPassword) {

      newErrors.passwordMatchError = "Passwords do not match";

    }



    if (

      newErrors.emailError ||

      newErrors.mobileNumberError ||

      newErrors.passwordMatchError

    ) {

      setValidationErrors(newErrors);

    } else {

      setValidationErrors({

        emailError: "",

        mobileNumberError: "",

        passwordMatchError: "",

      });

      const userData = {

        firstName: firstName,

        lastName: lastName,

        email: email,

        mobileNumber: mobileNumber,

        password: password,

      };

      axios.post("http://localhost:80/api/registration.php", userData);

      console.log(`UserData: ${JSON.stringify(userData)}`);

    }

  };



  return (

    <div className="register-container">

      <h1 className="register-heading">Register</h1>

      <form onSubmit={handleSubmit} className="register-form">

        <label className="register-label">

          <input

            type="text"

            placeholder="First Name"

            value={firstName}

            onChange={(e) => setFirstName(e.target.value)}

            className="register-input"

            required

          />

        </label>

        <br />

        <label className="register-label">

          <input

            type="text"

            placeholder="Last Name"

            value={lastName}

            onChange={(e) => setLastName(e.target.value)}

            className="register-input"

            required

          />

        </label>

        <br />

        <label className="register-label">

          <input

            type="email"

            placeholder="Email"

            value={email}

            onChange={(e) => setEmail(e.target.value)}

            className="register-input"

            required

          />

        </label>

        {validationErrors.emailError && (

          <p className="register-error">{validationErrors.emailError}</p>

        )}

        <br />

        <label className="register-label">

          <input

            type="tel"

            placeholder="Mobile Number"

            value={mobileNumber}

            onChange={(e) => setMobileNumber(e.target.value)}

            className="register-input"

            required

          />

        </label>

        {validationErrors.mobileNumberError && (

          <p className="register-error">{validationErrors.mobileNumberError}</p>

        )}

        <br />

        <label className="register-label">

          <input

            type="password"

            placeholder="Password"

            value={password}

            onChange={(e) => setPassword(e.target.value)}

            className="register-input"

            required

          />

        </label>

        <br />

        <label className="register-label">

          <input

            type="password"

            placeholder="Confirm Password"

            value={confirmPassword}

            onChange={(e) => setConfirmPassword(e.target.value)}

            className="register-input"

            required

          />

        </label>

        {validationErrors.passwordMatchError && (

          <p className="register-error">

            {validationErrors.passwordMatchError}

          </p>

        )}

        <br />

        <button type="submit" className="register-button">

          Register

        </button>

      </form>

      <p className="register-login-link">

        Already have an account? <Link to="/login">Login</Link>

      </p>

    </div>

  );

}



export default Register;

 

and this is my backend 

 

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "realestate";



header('Access-Control-Allow-Origin: http://localhost:3000');

header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

header('Access-Control-Allow-Headers: Content-Type');



$conn = mysqli_connect($servername, $username, $password, $dbname);




if (!$conn) {

  die("Connection failed: " . mysqli_connect_error());

}



$data = json_decode(file_get_contents('php://input'), true);



if (isset($data['name']) && isset($data['email']) && isset($data['mobileNumber']) && isset($data['password'])) {

  $name = $data['name'];

  $email = $data['email'];

  $mobileNumber = $data['mobileNumber'];

  $password = $data['password'];





  $stmt = mysqli_prepare($conn, "INSERT INTO `registration` (`name`,`email`,`mobileNumber`,`Password`) VALUES (?, ?, ?, ?)");

  mysqli_stmt_bind_param($stmt, "ssss", $name, $email, $mobileNumber, $password);



  if (mysqli_stmt_execute($stmt)) {

    $response = array('status' => 'success', 'message' => 'Data stored successfully!');

  } else {

    $response = array('status' => 'error', 'message' => 'Error: ' . mysqli_error($conn));

  }



  mysqli_stmt_close($stmt);

  mysqli_close($conn);





  header('Content-Type: application/json');

  echo json_encode($response);

}

?>

This is the screenshot of the table in database

image.png.aa5f391b063add1d40c26fd6dd1f5a2e.png

What is the error in the code that I have not been able to find please help me because no data is getting inserted in the database please help
 

Link to comment
Share on other sites

The data structure you are sending is:

const userData = {
  firstName: firstName,
  lastName: lastName,
  email: email,
  mobileNumber: mobileNumber,
  password: password,
};

While the data structure you are reading is:

$name = $data['name'];
$email = $data['email'];
$mobileNumber = $data['mobileNumber'];
$password = $data['password'];

Notice the difference in the fields?

Link to comment
Share on other sites

11 minutes ago, kicken said:

The data structure you are sending is:

const userData = {
  firstName: firstName,
  lastName: lastName,
  email: email,
  mobileNumber: mobileNumber,
  password: password,
};
 

While the data structure you are reading is:

$name = $data['name'];
$email = $data['email'];
$mobileNumber = $data['mobileNumber'];
$password = $data['password'];
 

Notice the difference in the fields?

2023-04-10_20-38.png.ab9078fd1bbe9ef1a3f2e0c542236fa8.pngimage.png.d3e5ced7c1dc6cad8441ab40ecc989f7.png

I fixed it but it is still not working 

Link to comment
Share on other sites

17 minutes ago, gula said:

2023-04-10_20-38.png.ab9078fd1bbe9ef1a3f2e0c542236fa8.pngimage.png.d3e5ced7c1dc6cad8441ab40ecc989f7.png

I fixed it but it is still not working 

If it's still not working then you didn't fix it. 🤔

 

echo json_decode(['Name' => $data['name'], 'email' => $data['email'], //... the rest]);

 

Edited by Strider64
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.