首页 > 解决方案 > 如何在 Angular 中显示 MySQL 数据

问题描述

我一直在尝试为我的 covid-19 timepass 学习一些 SQL,并且我设法制作了数据,但我现在陷入了困境,我迷失了如何用角度重复从我的 SQL 中获得的表下表中的数据库!,我查看了 W3School 和其他几个网站,但我没有得到它。

PHP

if($connectServer->connect_error){
    die("Connection failed :".$connectServer->connection_error);
}

$result = $connectServer->query("SELECT * FROM Users");

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"ID":"'  . $rs["userID"] . '",';
$outp .= '"First Name":"'  . $rs["FName"] . '",';
$outp .= '"Last Name":"'  . $rs["FName"] . '",';
$outp .= '"City":"'   . $rs["City"]        . '",';
$outp .= '"Email":"'. $rs["Email"]     . '"}';
}
$outp ='{"names":['.$outp.']}';

echo($outp);?>

HTML

<table ng-controller="customersCtrl" ng-app="myApp">
    <tr>
        <th>ID</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>City</th>
        <th>Email</th>
    </tr>
    <tr ng-repeat="a in names">
        <td>{{a.ID}}</td>
        <td>{{a.First Name}}</td>
        <td>{{a.LName}}</td>
        <td>{{a.City}}</td>
        <td>{{a.Email}}</td>
    </tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
      $http.get("php/fetchDATA.php")
      .then(function (response) {$scope.names = response.data.records;});
    });
</script>

获取数据.PHP

{"names":[{"ID":"32","First Name":"ValueFName","Last Name":"ValueFName","City":"ValueCity","Email":"ValueEmail"}, {"ID":"33","First Name":"ValueFName","Last Name":"ValueFName","City":"ValueCity","Email":"ValueEmail"},{"ID":" 34","First Name":"ValueFName","Last Name":"ValueFName","City":"ValueCity","Email":"ValueEmail"}]}

标签: phpmysqlangularjs

解决方案


您的每个代码中都有一些错误,例如变量{{a.First Name}}有空格并且{{a.LName}}没有在任何地方定义。

因此,您必须更改 php 中的变量声明才能使代码正常工作。

此外,您期望的响应必须具有变量记录,但您定义的 php 没有任何此类变量。因此,我建议您在提问之前再次阅读 PHP 和 Angular 教程。


推荐阅读