首页 > 解决方案 > 使用 PHP 将 mySQL 数据库中的数据显示到 vue.js 前端

问题描述

我目前正在尝试使用 php 在我的 vue.js 模板上的 xampp 上显示来自 mySQL 数据库的数据。我在网上找到了一个关于如何做到这一点的教程,但是在放置代码之后,数据没有显示,我的控制台也没有出现任何错误,所以我无法调试它不起作用的原因。有人可以帮我吗?

索引.php

<?php

//index.php

$connect = new PDO("mysql:host=localhost;dbname=test", "root", "");
$received_data = json_decode(file_get_contents("php://input"));
$data = array();
if($received_data->action == 'fetchall')
{
    $query = "
        SELECT * FROM tbl_sample 
        ORDER BY id DESC
    ";
    $statement = $connect->prepare($query);
    $statement->execute();
    while($row = $statement->fetch(PDO::FETCH_ASSOC))
    {
        $data[] = $row;
    }
    echo json_encode($data);
}

if($received_data->action == 'fetchSingle')
{
    $query = "
        SELECT * FROM tbl_sample 
        WHERE id = '".$received_data->id."'
    ";

    $statement = $connect->prepare($query);

    $statement->execute();

    $result = $statement->fetchAll();

    foreach($result as $row)
    {
        $data['id'] = $row['id'];
        $data['first_name'] = $row['first_name'];
        $data['last_name'] = $row['last_name'];
    }

    echo json_encode($data);
}

?>

我在我的dashboard.vue页面中这样调用它

仪表板.vue

  <table class="table table-bordered table-striped">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Edit</th>
    <th>Delete</th>
  </tr>
  <tr v-for="row in allData" :key="row">
    <td>{{ row.first_name }}</td>
    <td>{{ row.last_name }}</td>
    <td>
      <button
        type="button"
        name="edit"
        class="btn btn-primary btn-xs edit"
        @click="fetchData(row.id)"
      >Edit</button>
    </td>
    <td>
      <button
        type="button"
        name="delete"
        class="btn btn-danger btn-xs delete"
        @click="deleteData(row.id)"
      >Delete</button>
    </td>
  </tr>
</table>

export default {
  metaInfo: {
    // if no subcomponents specify a metaInfo.title, this title will be used
    title: "Dashboard v1",
    mixins: [clickaway]
  },
  components: {
    Notebook,
    Page,
    highcharts: Chart,
    CustomPie,
    CustomGuage,
    CommitChart
 },
 data() {
   return {
     allData: "",
     myModel: false,
     actionButton: "Insert",
     dynamicTitle: "Add Data",
 },

  mounted() {
    this.testQuery();
    this.getContacts();

  },

  methods: {
    fetchAllData: function() {
      axios
        .post("index.php", {
          action: "fetchall"
        })
        .then(function(response) {
          application.allData = response.data;
          console.log(response.data)
        });
    },
openModel: function() {
  application.first_name = "";
  application.last_name = "";
  application.actionButton = "Insert";
  application.dynamicTitle = "Add Data";
  application.myModel = true;
},

fetchData: function(id) {
  axios
    .post("index.php", {
      action: "fetchSingle",
      id: id
    })
    .then(function(response) {
      application.first_name = response.data.first_name;
      application.last_name = response.data.last_name;
      application.hiddenId = response.data.id;
      application.myModel = true;
      application.actionButton = "Update";
      application.dynamicTitle = "Edit Data";
    });
},

created: function() {
  this.fetchAllData();
},

};

mySQL 数据库看起来像这样 - 在此处输入图像描述

我不太了解 php 或数据库,有人可以告诉我哪里出错了。我已经输入了正确的数据库名称和详细信息,并且还在我的模板中安装了 axios

标签: phpmysqlvue.js

解决方案


似乎您可能会同时遇到一些问题。我建议首先独立测试以验证 PHP 代码在您的本地是否正常工作。通过带有http://localhost/index.php?action=fetch-all 的浏览器,具体取决于您项目中的位置,以查看您是否正在与数据库通信。我已经稍微修改了代码以通过 GET 查看结果。

<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=test", "root", "");
$received_data = json_decode(file_get_contents("php://input"), true);
$result = [];

if ($received_data->action === 'fetch-all' || $_GET['action'] === 'fetch-all') {

  $query = "SELECT *
            FROM tbl_sample
            ORDER BY id DESC";

  $statement = $connect->query($query);

  while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
    $result[] = $row;
  }

  echo json_encode($result);
}

浏览器中的响应应如下所示:

[{"id":"3","first_name":"Donna","last_name":"Huber"},{"id":"2","first_name":"Peter","last_name":"Parker"},{"id":"1","first_name":"John","last_name":"Smith"}]

我注意到一些缺少的大括号,不确定你是否在 vue 上工作了一些 Linting ......之后,更新 fecthAllData 函数:

methods: {    
    fetchAllData: function () {
        axios
          .get("index.php" + '?action=fetch-all')
          .then((response) => {
                this.allData = response.data;
                console.log('response', this.allData);
          });
      }, ...

如果您还没有看到任何结果,请检查浏览器中的网络选项卡,您应该能够看到在页面加载时触发了路由调用。希望我的话有所帮助。

更新 - PHP 内置 WebServer 方法:

上面的解决方案应该从默认的网络服务器端口(80)工作。如果使用 PHP 内置 Web 服务器,则需要为来自 Vue.js 的 API 调用做一些代理。

查看您是否安装了 Vue.cli(有关详细信息,请查看https://cli.vuejs.org/https://github.com/chimurai/http-proxy-middleware#proxycontext-config)。

正确安装后,为了将 API 调用从您的 Vue.js 应用程序移至提供 PHP 代码的不同端口,请在代理配置中添加以下行:

proxy: {
    "/api": "http://[::1]:8090"
}

Axios 调用也需要更新,例如:

.get("api" + '?action=fetch-all')

api urls ( /api) 调用将被重定向到端口8090(我使用了端口 8090,因为我不确定您的本地计算机当前占用了哪些端口)。

此时,您可以重试从浏览器访问 http://localhost:8090/?action=fetch-all(在为应用程序提供服务之后php -S localhost:8090),并从 Vue.js 应用程序获得相同的结果。


推荐阅读