Reputation: 69
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.
Upvotes: 2
Views: 588
Reputation: 11257
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!!!
Upvotes: 1