PHP数组发送React Native Fetch

时间:2019-07-10 03:07:26

标签: php react-native fetch react-native-flatlist

我是React-Native和PHP的新手,我试图将一个数组从PHP发送到REACT-NATIVE,结果是[object object]像PHP没有收到任何东西一样,问题是数据无法显示在屏幕上,PHP的功能运行良好,我与邮递员进行了测试,一切都很完美,但是在前面,我的代码是这样的:

export class Home extends Component {

  state = {
    data: []
  };

componentWillMount() {
  alert(this.fetchData());
    this.fetchData();
  }

  fetchData = async () => {
    const response = await fetch("http://localhost/APP/Chauffeur/Backendapp/api/Traitement/AffichageStation.php");
    const json = await response.json();
    this.setState({ data: json.results });
  };

 render() {
   return (
     <View style={styles.container}>
       <FlatList
         data={this.state.data}
         keyExtractor={(x, i) => i}
         renderItem={({ item }) =>
           <Text>
             {`${item.name.nom} ${item.name.adresse}`}
           </Text>}
       />
     </View>
   );
 }
}

const styles = StyleSheet.create({
 container: {
   marginTop: 15,
   flex: 1,
   justifyContent: "center",
   alignItems: "center",
   backgroundColor: "#F5FCFF"
 }
});
/*const styles = StyleSheet.create({
  container: {
    marginTop: 9,
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#CAD9E5",
  },
  go:{
    marginTop: 90,
    position:"absolute",
    color:"red"
  }
});*/

export default Home;

函数chau

<?php

$query = 'SELECT  A.idCH, A.idC, A.createdAt , S.nomStation as nom , S.adresse as adresse , C.quantite as quantite
    FROM Affectation A
    INNER JOIN Commande C ON A.idC=C.id
    INNER JOIN station S ON S.id=C.idS
    WHERE idCH=:idCH
         ORDER BY A.createdAt DESC';

$stmt = $this->conn->prepare($query);
$stmt->bindParam(':idCH', $this->idCH);

// Execute query
$stmt->execute();
if ($stmt->rowCount() > 0) {
    $stmt = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($stmt as $key => $value) {
        return json_encode($stmt);
    }
} else {
    return false;
}
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');
session_start();
include_once "../../config/Database.php";
include_once "../../models/Affectation.php";
$Database = new Database();
$db = $Database->connect();
$Affectation = new Affectation($db);

$Affectation->idCH = '105';
$results = $Affectation->chau();

echo $results;

?>

1 个答案:

答案 0 :(得分:0)

return循环中使用foreach语句,您最多只会返回第一个结果。

json_encode整个结果集并返回,如下所示:

$stmt->execute();
if($stmt->rowCount() > 0){
    return json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
//    foreach ($stmt as $key => $value) {
//       return json_encode($stmt);
//    }
}else{
    return false;
}

编辑:

我只是注意到您返回的是$stmt而不是$value,因此您实际上是在返回整个结果集。如果您只是得到一个空数组,则表明您的查询未返回任何结果