article

Saturday, March 26, 2022

ReactJS AutoComplete Textbox with PHP and Mysqli | Filter Search

ReactJS AutoComplete Textbox with PHP and Mysqli | Filter Search

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

run
C:\reactdev\myreactdev>npm start

CREATE TABLE `country` (
  `id` int(6) NOT NULL,
  `country` varchar(250) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `country` (`id`, `country`) VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica');

ALTER TABLE `country`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `country`
  MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'
 
ReactDOM.render(
  ,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { useState, useEffect } from "react";

function Search() {
  const [allcountry, setAllcountry] = useState([]);
  const [filterresult, setFilterresult] = useState([]);
  const [serachcountry, setSearchcountry] = useState("");

  const handlesearch = (event) => {
    const search = event.target.value;
    console.log(search);
    setSearchcountry(search);

    if (search !== "") {
      const filterdata = allcountry.filter((item) => {
        return Object.values(item)
          .join("")
          .toLowerCase()
          .includes(search.toLowerCase());
      });
      setFilterresult(filterdata);
    } else {
      setFilterresult(allcountry);
    }
  };

  useEffect(() => {
    const getcountry = async () => {
      const getres = await fetch("http://localhost/devtest/reactjs/country.php");
      const setcounty = await getres.json();
      console.log(setcounty);
      setAllcountry(await setcounty);
    };
    getcountry();
  }, []);

  return (
      <div className="container">
        <div className="row"><p><h3>ReactJS AutoComplete Textbox with PHP and Mysqli | Filter Search</h3></p>
          <div className="col-md-6 mb-3 mt-3">
            <input
              type="text"
              className="form-control"
              placeholder="Enter Keyword"
              onChange={(e) => {
                handlesearch(e);
              }}
            />
            <table className="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>Country ID </th>
                  <th>Country Name</th>
                </tr>
              </thead>
              <tbody>
                {serachcountry.length > 1
                  ? filterresult.map((filtercountry, index) => (
                      <tr key={index}>
                        <td> {filtercountry.id} </td>
                        <td> {filtercountry.country} </td>
                      </tr>
                    ))
                  : allcountry.map((getcon, index) => (
                      <tr key={index}>
                        <td> {getcon.id} </td>
                        <td> {getcon.country} </td>
                      </tr>
                    ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
  );
}

export default Search;
http://localhost/devtest/reactjs/country.php

country.php
//country.php
<?php
header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints:
$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "testingdb"; 

$con = mysqli_connect($host, $user, $password,$dbname);

$method = $_SERVER['REQUEST_METHOD'];


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
    case 'GET':
      $sql = "select * from country"; 
      break;
}

// run SQL statement
$result = mysqli_query($con,$sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'GET') {
    echo '[';
    for ($i=0 ; $i<mysqli_num_rows($result) ; $i++) {
      echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    echo ']';
}else {
    echo mysqli_affected_rows($con);
}

$con->close();

Related Post