Home > database >  Searching in Database and showing in react table
Searching in Database and showing in react table

Time:06-30

Hello guys i have this code in PHP which has path "http://localhost:80/ico/vypsani.php"

    $ico = $_POST['ico'];
    include_once("core.php");
    $sql = "SELECT * FROM ico WHERE ico = '$ico'";
    $result = mysqli_query($conn, $sql);
    $json_array = array();
    while($row = mysqli_fetch_assoc($result)){
         $json_array[]=$row;
    }
    echo json_encode($json_array);

in PHP i am searching row in database with input in React and its working, but i need to ge it into this table

import React,{useState, useEffect} from 'react';

const Data = () =>{
    const [item, setItem] = useState([]);
    useEffect(()=>{
        fetch("http://localhost:80/ico/vypsani.php")
        .then(res => res.json())
        .then(
            (result) => {
                setItem(result);
            }
         )
    },[])
    return (
        <div className="row">
                <table >
                    <thead className='thead-dark'>
                    <tr>
                    <th scope="col">ID</th>
                    <th scope="col">IČO</th>
                    <th scope="col">Název</th>
                    <th scope="col">Město</th>
                    <th scope="col">Ulice</th>
                    <th scope="col">Číslo Domovní</th>
                    <th scope="col">Číslo Orientační</th>
                    <th scope="col">Datum uložení</th>
                    </tr>
                    </thead>
                    <tbody>
                        {
                            item.map(item=>(
                                <tr key={item.ID}>
                                    <td>{item.ID}</td>
                                    <td>{item.ico}</td>
                                    <td>{item.nazev}</td>
                                    <td>{item.mesto}</td>
                                    <td>{item.ulice}</td>
                                    <td>{item.cisloDomovni}</td>
                                    <td>{item.cisloOrientacni}</td>
                                    <td>{item.datum}</td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
        </div>
    );
}

but it shows the row from database like this enter image description here and not in react table, i think because of the POST, thank you for answers

How react app looks like

import React from 'react';
import './App.css';
import Data from "./data/data.js";

function App() {
  return (
    <div className="App">
      <form action='http://localhost:80/ico/vypsani.php' method="post">
        <div className='form'>
        <h1>IČO</h1>
        <input name="ico" onKeyPress={(event) => {
          if (!/[0-9]/.test(event.key)) {
            event.preventDefault();
            alert("Zadávat lze pouze čísla")
          }
        }}
    />
        <h1>Název firmy</h1>
        <input name="nazev" type="text"></input>
        <br></br>
        <button type="submit" name='submit' value="vyhledat">Vyhledat</button>
        <br></br>
        <button type="submit" name='submit' value="odeslat">Odeslat</button>
        <br></br>
        </div>
        <h1>Výpis z Databáze</h1>
        <Data/>
      </form>
    </div>
  );
}

export default App;

CodePudding user response:

Change your useEffect like this

useEffect(()=>{
    fetch("http://localhost:80/ico/vypsani.php")
    .then(result => {
            setItem(result);
            console.log(result);
        }
     )
     .catch(error => {
        console.log(error)
      })
},[])

and table body like this

<tbody>
                    {
                       item && item?.map(ele=>(
                            <tr key={ele.ID}>
                                <td>{ele.ID}</td>
                                <td>{ele.ico}</td>
                                <td>{ele.nazev}</td>
                                <td>{ele.mesto}</td>
                                <td>{ele.ulice}</td>
                                <td>{ele.cisloDomovni}</td>
                                <td>{ele.cisloOrientacni}</td>
                                <td>{ele.datum}</td>
                            </tr>
                        ))
                    }
                </tbody>

I hope this should work

CodePudding user response:

POSTing form to php page is not the correct way to do this. Please read answer to this question: Send a ReactJS form to a PHP page

To get your code to work, you can remove form in the html and handle the request using fetch only. Also, change $ico = $_POST['ico']; to $ico = $_GET['ico']; in your php file

  import React from 'react';

class Test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      tableData: [],
      ico: ''
    };
  }

  handleInput = event => {
    this.setState({ ico: event.target.value });
  };

  logValue = () => {
    fetch("http://localhost:80/ico/vypsani.php?ico="   this.state.ico)
    .then(res => res.json())
    .then(
      (result) => {
        this.setState(state => state.tableData = result);
      }
    )
    .catch(err => {
      throw err
    });
  }; 
  render() {
    return (
      <div className="App">
        <div className='form'>
          <h1>IČO</h1>
          <input name="ico" onKeyPress={(event) => {
            if (!/[0-9]/.test(event.key)) {
              event.preventDefault();
              alert("Zadávat lze pouze čísla")
            }
          }}
          />
          <h1>Název firmy</h1>
          <input name="nazev" onChange={this.handleInput} type="text"></input>
          <br></br>

          <button type="submit" name='submit' onClick={this.logValue} value="vyhledat">Vyhledat</button>
          <br></br>
          <button type="submit" name='submit' value="odeslat">Odeslat</button>
          <br></br>
        </div>
        <h1>Výpis z Databáze</h1>
        <div  >
          <table >
            <thead className='thead-dark'>
              <tr>
                <th scope="col">ID</th>
                <th scope="col">IČO</th>
                <th scope="col">Název</th>
                <th scope="col">Město</th>
                <th scope="col">Ulice</th>
                <th scope="col">Číslo Domovní</th>
                <th scope="col">Číslo Orientační</th>
                <th scope="col">Datum uložení</th>
              </tr>
            </thead>
            <tbody>
              {
                this.state.tableData.map(item => (
                  <tr key={item.ID}>
                    <td>{item.ID}</td>
                    <td>{item.ico}</td>
                    <td>{item.nazev}</td>
                    <td>{item.mesto}</td>
                    <td>{item.ulice}</td>
                    <td>{item.cisloDomovni}</td>
                    <td>{item.cisloOrientacni}</td>
                    <td>{item.datum}</td>
                  </tr>
                ))
              }
            </tbody>
          </table>
        </div>

      </div>

    );
  }
}
export default Test;
  • Related