0
Well I’m having difficulty and I haven’t found a solution yet, wanted to develop a crud using Reactjs + PHP + Mysql; I made a php file that returns a JSON object so I can access it from React.
<?php
//Header
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
//
include '../conf/database.php';
include '../objects/carro.php';
//
$database = new Database();
$db = $database->getConnection();
//
$carro = new Carro($db);
//
$stmt = $carro->read();
$num = $stmt->rowCount();
//
if($num>0){
$carros_arr=array();
$carros_arr["records"]=array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$carros_arr["records"][$id] = array(
"id" => $id,
"nome" => $nome,
"descricao" => html_entity_decode($descricao),
"marca" => $marca,
"valor" => $valor
);
}
http_response_code(200);
echo json_encode($carros_arr);
}else {
http_response_code(404);
echo json_encode(
array("message" => "No products found.")
);
}
?>
And the React file:
import React, {Component} from 'react';
import './styles.css';
import axios from 'axios';
export default class Main extends Component{
state = {
carros : [],
isLoading : true
}
componentDidMount(){
this.loadCars();
}
loadCars(){
const url = "http://localhost/apihunt/carro/read.php";
//METODO 1
/*axios(url)
.then(response => response.data)
.then(data => {
this.setState({
carro : data,
isLoading : false
});
});*/
//METODO 2
/*const response = axios(url);
const {records} = response.data;
this.setState({
carro : records
})*/
//METODO 3
fetch("http://localhost/apihunt/carro/read.php")
.then((response) => response.json())
.then((responseJson) => (
this.setState({
carros : responseJson
})
));
console.log(this.state.carros);
}
render(){
return(
<div className="list-item">
</div>
);
}
}
None of the methods are working, and I also tried to use async-await;
Any suggestions or a CRUD using React, PHP and mysql?
If you put
http://localhost/apihunt/carro/read.php
directly in the browser url for JSON?– Sergio
yes, the php code is running perfectly , and Next in js is assigning the array to the state, the problem is just when I use the map in the array says "Object.map is not Function"
– Everton Fernandes
Answer : https://stackoverflow.com/questions/56114358/react-js-phpmysql-records-map-is-not-a-function/56115646#56115646 The problem was in php.
– Everton Fernandes