简体   繁体   中英

How to check if user exists in database using ReactJs, PHP and MySQL?

I have created a login page in Reactjs and I have a login_check code in PHP. Now I have to check if the user exists in the database and if exists I want to create a token otherwise no. I used jquery to post the data when the user enters his/her details. But every time it gives a sorry message in the console don't know whether the data is getting posted to PHP or not. Here's my code.

Sigin.js

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom'
import axios from 'axios'
import $ from 'jquery'
class Signin extends Component {
constructor(props)
{
    super(props);
    const token = localStorage.getItem("token")

    let loggedIn = true
    if(token == null)
    {
        loggedIn = false
    }

    this.state = {
        email: '',
        password: '',
        loggedIn
    }

    this.onChange = this.onChange.bind(this)
    this.submitForm = this.submitForm.bind(this)
}

onChange(e){
    this.setState({
        [e.target.name] : e.target.value
    })
}


submitForm(e){
    e.preventDefault();
    // const { email, password } = this.state

    // if(email === "admin@123" && password === "admin")
    // {
    //     localStorage.setItem("token", "loggedIn")
    //     this.setState({
    //         loggedIn: true
    //     })
    //     console.log("Logged In!")
    // }
    // else
    // {
    //     alert("Invalid email or password!");
    //     console.log("Invalid email or password!")
    // }


        $.post("http://localhost/php-react-rest-api-crud/login_check.php", function(data){
                if(data === "1")
                {
                    localStorage.setItem("token", "loggedIn")
                    console.log("success!");
                }
                else if(data === "0")
                {
                    console.log("sorry!");
                }
            })

}
render() {
    if(this.state.loggedIn)
    {
        return <Redirect to = "/admin" /> 
    }
    return (

        <div>
            <h1>Login</h1>

            <form onSubmit={this.submitForm}>
                <input type="email" name="email" placeholder="Enter email" value={this.state.email} onChange={this.onChange}/>
                <input type="password" name="password" placeholder="Enter Password" value={this.state.password} onChange={this.onChange}/>
                <br />
                <input type="submit"/>
            </form>
        </div>
    );
  }
}

export default Signin;

login_check.php

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token');
header("Access-Control-Allow-Methods: GET, POST");

$conn = mysqli_connect("localhost", "root", "", "farmer_portal");
if(!$conn)
{
    die('Connection error'.mysqli_connect_errno());
}


if((!isset($_POST['email'])) && (!isset($_POST['password'])))
{
   echo "0"; 
   exit();
}

$myemail = $_POST['email'];
$mypassword= $_POST['password'];


$email = "SELECT * FROM signup WHERE email='$myemail' ";
$pass = "SELECT * FROM signup WHERE password='$mypassword' ";

$myemail = stripslashes($email);
$mypassword = stripslashes($password);

$res_e = mysqli_query($conn,$myemail);
$res_p = mysqli_query($conn,$mypassword);

if(mysqli_num_rows($res_p) > 0 && mysqli_num_rows($res_e) > 0)
{
echo "1";
}
else
{
  echo "0";
}

?>

A little bit about your code first, if I may

I see that you import Axios but never use it, instead using jQuery to post your ajax request. If that's all you're using jQuery for, I highly recommend dumping it and sticking to Axios. It's great at what it does.

Secondly, whenever possible, avoid multiple SQL requests if you can get away with fewer or, even better, only one. These two requests:

$email = "SELECT * FROM signup WHERE email='$myemail' ";
$pass = "SELECT * FROM signup WHERE password='$mypassword' ";

Should be made into one:

$user_info = "SELECT * FROM signup WHERE email='$myemail' AND password='$mypassword'";

You should also check the contents of $myemail and $mypassword . stripslashes() isn't nearly enough to prevent mysql injections. More on that subject here .

Never trust user input. Always check you're getting what you're expecting, in your case that $myemail is indeed an email and that password is indeed a string. PHP provides two functions to that end, filter_var($myemail, FILTER_VALIDATE_EMAIL) and is_string($mypassword) .

Finally, and maybe the most important point: don't store non-hashed passwords . PHP provides password_hash($mypassword) to store passwords and password_verify($mypassword) to check your user input against database.

Now to address your question

The answer lies in your JS code :

$.post("http://localhost/php-react-rest-api-crud/login_check.php", function(data) {
    // ...
});

Both in Axios and jQuery, the second parameter of the post() function should be your data, meaning user email and password. But here, you don't send any data, you jump straight to handling the response to your AJAX request. Hence why PHP returns "0".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM