I am using react js on localhost:3000 and I am using PHP on localhost:8080,now I wanted to fetch mysql table data through AXIOS API to the react js page named DataandForm.jsx. I have a PHP page index.php where i am fetching MYSQL table rows which runs on localhost:8080/data/index.php, Now how can I take that data available in index.php to DataandForm.jsx using AXIOS?
DataandForm.jsx
import React from 'react'
class DataandForm extends React.Component{
constructor()
{
super()
this.state={
row:[]
}
}
componentDidMount()
{
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('http://localhost:8080/data/index.php')
.then( response =>{
// handle success
console.log(response);
this.setState({row:response.data});
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
render()
{
return(
<div className="container">
<div className="row">
<div className="col-sm-6">
{this.state.row.map(datum=>
<div className="row">
<div className="col-sm-4">key={datum.id}</div>
<div className="col-sm-4">data1={datum.data1}</div>
<div className="col-sm-4">data2={datum.data2}</div>
</div>
)}
</div>
<div className="col-sm-10 offset-sm-2"><br/>
<form class="form-inline" action=" " method="post" >
<div class="form-group">
<label for="email">FIRSTNAME:</label>
<input type="text" name="data1" class="form-control" id="email" />
</div>
<div class="form-group">
<label for="pwd">LASTNAME:</label>
<input type="text" name="data2" class="form-control" id="pwd" />
</div>
<button type="submit" class="btn btn-danger">Submit</button>
</form>
</div>
</div>
</div>
)
}
}
export default DataandForm
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM datum";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "DATA1: " . $row["data1"]. " - DATA2: " . $row["data2"]. "<br>";
}
} else {
echo "0 results";
}
?>
Here, I have an index.php page that just fetches some rows from the table and it runs on http://localhost:8080/data/index.php . I have also a DataandForm.jsx file that's trying to fetch the data from the PHP file using the AXIOS api.
I wanted to fetch rows from table to react front end through php with an api call. Should I make the fetch rows to a json then bring to react? How can I make this happen?