Php angularJS 项目未在简单的 html 表格中显示数据

标签 php html mysql angularjs

我是 Php 和 AngularJS 新手...我在这些链接上关注了 2 个有趣的教程:

https://www.roytuts.com/rest-api-crud-example-in-php-mysql/

https://www.roytuts.com/angularjs-php-rest-crud-example/

第一个运行顺利,第二个在html表中没有显示数据库数据,不知道为什么。

以下所有项目文件: 文件db.php

<?php

class Db {

    private $host = "localhost";
    private $db_name = "crudtests";
    private $username = "root";
    private $password = "";
    public $conn;

    // get the database connection
    public function getConnection() {
        $this->conn = null;

        try {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        } catch (PDOException $exception) {
            echo "Database connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }

}

?>

文件department.php

<?php

/**
 * Description of Department
 *
 * @author
 */
class Department
{

    // database connection and table name
    private $conn;

    private $table_name = "department";

    // object properties
    public $id;

    public $name;

    // constructor with $db as database connection
    public function __construct($db)
    {
        $this->conn = $db;
    }

    // reads all departments
    function read()
    {
        // query to select all
        $query = "SELECT d.dept_id, d.dept_name
            FROM
                " . $this->table_name . " d
            ORDER BY
                d.dept_id";
        // prepare query statement
        $stmt = $this->conn->prepare($query);
        // execute query
        $stmt->execute();
        return $stmt;
    }

    // create department
    function create()
    {
        // query to insert record
        $query = "INSERT INTO
                " . $this->table_name . "
            SET
                dept_name=:name";

        // prepare query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->name = htmlspecialchars(strip_tags($this->name));

        // bind values
        $stmt->bindParam(":name", $this->name);

        // execute query
        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }

    // update the department
    function update()
    {
        // update query
        $query = "UPDATE
                " . $this->table_name . "
            SET
                dept_name = :name
            WHERE
                dept_id = :id";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->name = htmlspecialchars(strip_tags($this->name));
        $this->id = htmlspecialchars(strip_tags($this->id));

        // bind new values
        $stmt->bindParam(':name', $this->name);
        $stmt->bindParam(':id', $this->id);

        // execute the query
        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }

    // delete the department
    function delete() {
        // delete query
        $query = "DELETE FROM " . $this->table_name . " WHERE dept_id = ?";

        // prepare query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->id = htmlspecialchars(strip_tags($this->id));

        // bind id of record to delete
        $stmt->bindParam(1, $this->id);

        // execute query
        if ($stmt->execute()) {
            return true;
        }

        return false;
    }
}

?>

文件读取.php

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
require_once '../../config/db.php';
require_once 'Department.php';

// instantiate database and department object
$database = new Db();
$db = $database->getConnection();

// initialize object
$department = new Department($db);

// query department
$stmt = $department->read();
$num = $stmt->rowCount();

// check if more than 0 record found
if ($num > 0) {
    // department array
    $department_arr = array();
    $department_arr["records"] = array();

    // retrieve table contents
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // extract row
        extract($row);
        $department_item = array(
            "id" => $row['dept_id'],
            "name" => $row['dept_name']
        );
        array_push($department_arr["records"], $department_item);
    }
    echo json_encode($department_arr);
} else {

   echo json_encode(array(
        "message" => "No products found."
    ));
}
?>

文件app.js

/**
 * New module creation
 */

'use strict';

var app = angular.module('myCrudApp', []);

文件departmentController.js

/**
 *  Controller to handle user’s request/response
 */

'use strict';

angular.module('myCrudApp').controller('DepartmentController', ['$scope', 'DepartmentService', function($scope, DepartmentService) {
    var self = this;
    self.department = { id: null, name:'' };
    self.departments = [];

    self.submit = submit;
    self.edit = edit;
    self.remove = remove;
    self.reset = reset;


    findAllDepartments();

    function findAllDepartments(){
        DepartmentService.findAllDepartments()
            .then(
            function(d) {
                self.departments = d;
            },
            function(errResponse){
                console.error('Error while fetching departments');
            }
        );
    }

    function createDepartment(department){
        DepartmentService.createDepartment(department)
            .then(
            findAllDepartments,
            function(errResponse){
                console.error('Error while creating department');
            }
        );
    }

    function updateDepartment(department){
        DepartmentService.updateDepartment(department)
            .then(
            findAllDepartments,
            function(errResponse){
                console.error('Error while updating department');
            }
        );
    }

    function deleteDepartment(id){
        DepartmentService.deleteDepartment(id)
            .then(
            findAllDepartments,
            function(errResponse){
                console.error('Error while deleting department');
            }
        );
    }

    function submit() {
        if(self.department.id===null){
            console.log('Saving New Department', self.department);
            createDepartment(self.department);
        }else{
            updateDepartment(self.department);
            console.log('Department updated with id ', self.department.id);
        }
        reset();
    }

    function edit(id){
        console.log('id to be edited', id);
        for(var i = 0; i < self.departments.length; i++){
            if(self.departments[i].id === id) {
                self.department = angular.copy(self.departments[i]);
                break;
            }
        }
    }

    function remove(id){
        console.log('id to be deleted', id);
        if(self.department.id === id) {//clean form if the department to be deleted is shown there.
            reset();
        }
        deleteDepartment(id);
    }


    function reset(){
        self.department={id:null, name:''};
        $scope.myForm.$setPristine(); //reset Form
    }

}]);

文件departmentServices.php

/**
 * AngularJS service to communicate with Server
 */

'use strict';

angular.module('myCrudApp').factory('DepartmentService', ['$http', '$q', function($http, $q){

    var REST_SERVICE_URI = 'http://localhost/workspace/crudRestEsempio2/';

    var factory = {
        findAllDepartments: findAllDepartments,
        createDepartment: createDepartment,
        updateDepartment: updateDepartment,
        deleteDepartment: deleteDepartment
    };

    return factory;

    function findAllDepartments() {
        var deferred = $q.defer();
        $http.get(REST_SERVICE_URI+'restObjects/department/read.php')
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while fetching departments');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }

    function createDepartment(department) {
        var deferred = $q.defer();
        $http.post(REST_SERVICE_URI+'restObjects/department/create.php', department)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while creating department');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }


    function updateDepartment(department) {
        var deferred = $q.defer();
        $http.put(REST_SERVICE_URI+'restObjects/department/update.php', department)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while updating department');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }

    function deleteDepartment(id) {
        var deferred = $q.defer();
        $http.delete(REST_SERVICE_URI+'restObjects/department/delete.php?id='+id)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while deleting department');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }

}]);

有谁有耐心帮我找出问题所在吗?

我使用了一些 console.log() 函数来调试,“read.php”页面完美地返回了 JSON 数据。

我不会报告 create.php、update.php 和 delete.php 文件,因为它们并不重要。 (仅供引用,html 页面使用“添加”按钮成功在数据库中创建了新记录,因此这不是数据库连接问题)。

最佳答案

问题已解决。

在read.php中创建JSON对象时,

echo json_encode($department_arr);

需要

echo json_encode($department_arr["records"]);

如果不这样做,则 JSON 对象以错误的格式创建,并且 Angular 绑定(bind)不起作用。

现在完美运行。

关于Php angularJS 项目未在简单的 html 表格中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49239439/

相关文章:

php - Symfony2 和后台进程

javascript - 如何使用 Array.from 和 forEach 从多个表单字段值中获取值

php - Symfony - 如何知道控制台命令是从 Controller 运行还是从终端运行?

PHP IRR(内部 yield )财务函数

PHP SQL : How to save data to multiple database from one html form OR how to copy data from one database to another database automatically

javascript - 链接在 Bootstrap 导航栏中不起作用的菜单项

html - 段落换行后有空格

php - 从 MySQL 表中获取列名

java - 如何合并 10 万条 MySQL 行

php - MySQL 返回 -0001 作为年份