繁体   English   中英

如何从reactjs中获取mysql的数据?

[英]How to fetch data from mysql in reactjs?

我希望能够从 mysql 数据库中获取我的数据。 当我运行代码时,我的列表似乎是空的。 我做错了什么。 我的 core2_php.php 似乎运行良好。 我觉得问题出在这个 list.js 中。 将不胜感激任何帮助谢谢。

class List extends React.Component {
     //initialize an object's state in a class
      constructor(props) {
        super(props)
          this.state = {
            data: []
              }
      }
      //ComponentDidMount is use to Connect a React app to external applications, such as web APIs or JavaScript functions
      componentDidMount(){
        //get request
        axios.get('http://localhost/core2_php.php').then(res => 
        {
        this.setState({data: res.data});
           }); 
        
        }
  render() {
   
    return (
     
      <div className="maincontainer">
       
        <h1 className="mr-5 ml-5 mt-5">LIST</h1>
        <div className="container mb-5 mt-5 text-left">
        
        <table class="table table-hover">
          <thead>
            <tr>
              <th>First Name</th>
              <th>Last Name</th>
              
            </tr>
          </thead>
          <tbody>
          <tbody>
        {this.state.data.map(result => {
          return (
            <tr>
              <td>{result.firstname}</td>
              <td>{result.lastname}</td>
            </tr>
          );
        })}
      </tbody>   
          </tbody>
        </table>
      </div>
      </div>   
)
};
}
export default List;

这是我的 code2_php.php 我是编码新手,所以我想知道如何检查 php 代码以查看它是否正常工作。

<?php
    $servername = "localhost";
    $username   = "root";
    $password   = "";
    $dbname     = "user";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
        $trp = mysqli_query($conn, "SELECT * from userdata");
        $rows = array();
        while($r = mysqli_fetch_assoc($trp)) {
            $rows[] = $r;
        }
        print json_encode($rows); //convert php data to json data
    ?>

你能在你使用json-encode 的地方添加php文件吗?或者只是告诉你如何返回你的响应。

在 php 你应该只echo json_encode(['data' => $data]); (不返回)其中 $data - 来自 db 的结果数组。

您可以使用var_dump()进行调试。

只需将您的代码添加到 core2_php 中的 function 并调用var_dump(funcName()) ,其中您的 funcName() - 您的 function 名称。 您会看到类型以及您得到的响应是什么。 之后,您只需在浏览器中打开 php 即可查看结果。

并将您的提取更改为以下代码:

    $trp = mysqli_query($conn, "SELECT * from userdata");
    $rows = mysqli_fetch_all($trp, MYSQLI_ASSOC); //fetching data to an associative array
    echo json_encode($rows);

你会得到一个数组作为 response.data ----> Array([0]: 1, ....) 你可以在 JS 中使用console.log()来显示你对浏览器控制台的响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM