2

Please help me to make simple rest api in php to fetch data from the database and display into react js

I have 3 columns name,department and marks. here is my php code -

<?php 

header("Content-Type: application/json; charset=UTF-8");
$con = mysqli_connect("mysql1004.mochahost.com","a310387_task_for","task_force","a310387_task_force");

    $query=mysqli_query($con,'select * from student');
$json_array=array();
while($rows=mysqli_fetch_assoc($query)){
    $json_array[]=$rows;
 }
 echo json_encode($json_array);

 ?>

and here is my react code -

 componentDidMount(){
    fetch('http://veomit.com/test/zend/api/fetch.php')
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                });
    });
  }

displaying like-

 <tbody>
            <tr>
              {
                        this.state.UserData.map(function(item, key) {             
                        return (
                                <tr key = {key}>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                                </tr>
                            )
                        })
                    }
            </tr>
          </tbody>

please help me to correct this. thanks in advance.

1 Answer 1

1

Working code

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    userData: []
  };
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts") // could be any rest get url
      .then(response => response.json())
      .then(result =>
        this.setState({
          userData: result
        })
      );
  }
  render() {
    return (
      <div className="App">
        <table>
          <tbody>
            {this.state.userData.map((data, key) => {
              return (
                <tr key={key}>
                  <td>{data.userId}</td> // column data received
                  <td>{data.title}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Hope that helps!!!

Sign up to request clarification or add additional context in comments.

1 Comment

my react code is working fine but i think my rest api is wrong... so please help me correct my api

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.