ReactJS Simple Project with MySQL and PHP – Part 3

Steps:

1. Create a folder named react-php in htdocs folder to create PHP files to communicate with mysql database.

2. Create another folder api under react-php.

3. Go to api folder and create .htaccess file with the following code


RewriteEngine On
#RewriteBase /api/
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

4. Create a php file named config.php for database connection and add the following code.


<?php
$db = new mysqli("localhost","root","","reactdb");
if(!$db) die("database connection error");
?>

5. Create index.php and add the following code.


<?php 

$type = $_GET['tp']; 
if($type=='signup') signup(); 
elseif($type=='login') login(); 
elseif($type=='feed') feed(); 
elseif($type=='feedUpdate') feedUpdate(); 
elseif($type=='feedDelete') feedDelete(); 
function login() 
{ 
       require 'config.php'; 
       $json = json_decode(file_get_contents('php://input'), true); 
       $username = $json['username']; $password = $json['password']; 
       $userData =''; $query = "select * from users where username='$username' and password='$password'"; 
       $result= $db->query($query);
       $rowCount=$result->num_rows;
             
        if($rowCount>0)
        {
            $userData = $result->fetch_object();
            $user_id=$userData->user_id;
            $userData = json_encode($userData);
            echo '{"userData":'.$userData.'}';

            
        }
        else 
        {
            echo '{"error":"Wrong username and password"}';
        }

    
}



function signup() {
    
        require 'config.php';

              
        $json = json_decode(file_get_contents('php://input'), true);
        $username = $json['username'];
        $password = $json['password'];
        $email = $json['email'];
        $name = $json['name'];

        $username_check = preg_match("/^[A-Za-z0-9_]{4,10}$/i", $username);
        $email_check = preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/i', $email);
        $password_check = preg_match('/^[A-Za-z0-9!@#$%^&*()_]{4,20}$/i', $password);
       
        if($username_check==0) 
            echo '{"error":"Invalid username"}';
        elseif($email_check==0) 
            echo '{"error":"Invalid email"}';
        elseif($password_check ==0) 
            echo '{"error":"Invalid password"}';

        elseif (strlen(trim($username))>0 && strlen(trim($password))>0 && strlen(trim($email))>0 && 
            $email_check>0 && $username_check>0 && $password_check>0)
        {
           

            $userData = '';
            
            $result = $db->query("select * from users where username='$username' or email='$email'");
            $rowCount=$result->num_rows;
            //echo '{"text": "'.$rowCount.'"}';
           
            if($rowCount==0)
            {
                                
                $db->query("INSERT INTO users(username,password,email,name)
                            VALUES('$username','$password','$email','$name')");

                $userData ='';
                $query = "select * from users where username='$username' and password='$password'";
                $result= $db->query($query);
                $userData = $result->fetch_object();
                $user_id=$userData->user_id;
                $userData = json_encode($userData);
                echo '{"userData":'.$userData.'}';
            } 
            else {
               echo '{"error":"username or email exists"}';
            }

        }
        else{
            echo '{"text":"Enter valid data2"}';
        }
   
}


function feed(){
    
    require 'config.php';
    $json = json_decode(file_get_contents('php://input'), true);
    $user_id=$json['user_id'];
    
    $query = "SELECT * FROM feed WHERE user_id=$user_id ORDER BY feed_id DESC LIMIT 10";
    //$query = "SELECT * FROM feed ";
    $result = $db->query($query); 

    $feedData = mysqli_fetch_all($result,MYSQLI_ASSOC);
    $feedData=json_encode($feedData);
    
    echo '{"feedData":'.$feedData.'}';
    
   
}


function feedUpdate(){

    require 'config.php';
    $json = json_decode(file_get_contents('php://input'), true);
    $user_id=$json['user_id'];
    $feed=$json['feed'];
    
    $feedData = '';
    if($user_id !=0)
    {
        $query = "INSERT INTO feed ( feed, user_id) VALUES ('$feed','$user_id')";
        $db->query($query);              
    }
    $query = "SELECT * FROM feed WHERE user_id=$user_id ORDER BY feed_id DESC LIMIT 10";
    $result = $db->query($query); 

    $feedData = mysqli_fetch_all($result,MYSQLI_ASSOC);
    $feedData=json_encode($feedData);
    
    echo '{"feedData":'.$feedData.'}';

}

function feedDelete(){
    require 'config.php';
    $json = json_decode(file_get_contents('php://input'), true);
    $user_id=$json['user_id'];
    $feed_id=$json['feed_id'];
         
    $query = "Delete FROM feed WHERE user_id=$user_id AND feed_id=$feed_id";
    $result = $db->query($query);
    if($result)       
    {        
        echo '{"success":"Feed deleted"}';
    } else{
     
        echo '{"error":"Delete error"}';
    }
       
       
    
}

?>

6. Create UserFeed.css under UserFeed folder with the following code.


time{
color:#666666 !important;
font-size: 13px;
font-family: 'Georgia', 'Times New Roman', Times, serif
}
input[type="text"]{
height: 50px;
}
b{
display: block
}
.people-you-might-know{
padding:0 !important;
margin-bottom:10px;
border-radius: 5px;
}
.btn-color{
background-color: red;
}
.edit-btn-color{
background-color: green;
}

7. Create UserFeed.js under UserFeed folder with the following code.


import React, {Component} from 'react';
import Linkify from 'react-linkify';
import './UserFeed.css';
//import TimeAgo from 'react-timeago';
class UserFeed extends Component {

constructor(props){
super(props);
}

render() {

let userFeed = this.props.feedData
.map(function (feedData, index) {
return (
<div className="medium-12 columns" key={index}>

<div className="people-you-might-know">

<div className="row add-people-section">
<div className="small-12 medium-10 columns about-people">

<div className="about-people-author">
<p className="author-name">
<b>{this.props.name}</b>
<Linkify>{feedData.feed}</Linkify>
<br/>

</p>

</div>
</div>
<div className="small-12 medium-2 columns add-friend">

<div className="add-friend-action">
<button id="del" className="button small btn-color" onClick={this.props.deleteFeed} data={feedData.feed_id} value={this.props.index} >
<i className="fa fa-user-times" aria-hidden="true"></i>
Delete
</button>
</div>
</div>
</div>
</div>
</div>
)
}, this);

return (
<div>
{userFeed}

</div>
);
}

}

export default UserFeed;

8. Modify Home.js to add UserFeed.js


import React, {Component} from 'react';
import {Redirect} from 'react-router-dom';
import './Home.css';
import {PostData} from '../../services/PostData';
import UserFeed from "../UserFeed/UserFeed";
import { confirmAlert } from 'react-confirm-alert';
import '../../styles/react-confirm-alert.css';

class Home extends Component {

constructor(props) {
super(props);

this.state = {
data:[],
userFeed: '',
redirectToReferrer: false,
name:'',
};

this.getUserFeed = this.getUserFeed.bind(this);
this.feedUpdate = this.feedUpdate.bind(this);
this.onChange = this.onChange.bind(this);
this.deleteFeed = this.deleteFeed.bind(this);
this.deleteFeedAction = this.deleteFeedAction.bind(this);
this.logout = this.logout.bind(this);
}

componentWillMount() {

if(sessionStorage.getItem("userData")){
this.getUserFeed();
}

else{
this.setState({redirectToReferrer: true});
}

}

feedUpdate(e) {

e.preventDefault();
let data = JSON.parse(sessionStorage.getItem("userData"));
let postData = { user_id: data.userData.user_id, feed: this.state.userFeed };
if (this.state.userFeed) {
PostData('feedUpdate', postData).then((result) => {
let responseJson = result;
this.setState({data: responseJson.feedData});
});
}
}

deleteFeed(e){

confirmAlert({
title: 'Delete Feed',
message: 'Are you sure to delete this feed.',
buttons: [
{
label: 'Yes',
onClick: () => this.deleteFeedAction(e)
},
{
label: 'No',
onClick: () => alert('Click No')
}
]
});

}

deleteFeedAction(e){

let updateIndex=e.target.getAttribute('value');

let feed_id=document.getElementById("del").getAttribute("data");

let data = JSON.parse(sessionStorage.getItem("userData"));

let postData = { user_id: data.userData.user_id,feed_id: feed_id };
if (postData) {

PostData('feedDelete', postData).then((result) => {
this.state.data.splice(updateIndex,1);
this.setState({data:this.state.data});

if(result.success){

alert(result.success);
}
else
alert(result.error);

});
}
}

editFeed(e){

alert("j");
}

getUserFeed() {

let data = JSON.parse(sessionStorage.getItem("userData"));
this.setState({name:data.userData.name});
let postData = { user_id: data.userData.user_id};

if (data) {
PostData('feed', postData).then((result) => {
let responseJson = result;
if(responseJson.feedData){
this.setState({data: responseJson.feedData});
console.log(this.state);
}
});
}

}

onChange(e){
this.setState({userFeed:e.target.value});
}
logout(){
sessionStorage.setItem("userData",'');
sessionStorage.clear();
this.setState({redirectToReferrer: true});
}

render() {
if (this.state.redirectToReferrer) {
return (<Redirect to={'/login'}/>)
}

return (
<div className="row" id="Body">
<div className="medium-12 columns">
<a href="#" onClick={this.logout} className="logout">Logout</a>
<form onSubmit={this.feedUpdate} method="post">
<input name="userFeed" onChange={this.onChange} value={this.state.userFeed} type="text" placeholder="Write your feed here..."/>
<input
type="submit"
value="Post"
className="button"
onClick={this.feedUpdate}/>
</form>

</div>
<UserFeed feedData = {this.state.data} deleteFeed = {this.deleteFeed} name={this.state.name}/>

</div>
);
}
}

export default Home;

9. Run the app from the browser.