dtqi87613 2018-03-12 15:53
浏览 55

Php angularJS项目没有在简单的html表中显示数据

I'm a Php and AngularJS newbie... I followed 2 interesting tutorials on these links:

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

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

First one works smoothly, second one is not showing database data in the html table, don't know why.

Following all project files: File 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;
    }

}

?>

File 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;
    }
}

?>

File read.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."
    ));
}
?>

File app.js

/**
 * New module creation
 */

'use strict';

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

File 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
    }

}]);

File 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;
    }

}]);

Does anyone has the patience to help me find what's wrong?

I used some console.log() functions to debug and JSON data is perfectly returned by the "read.php" page.

I'm not reporting create.php, update.php, and delete.php files because are not significant. (FYI the html page successfully creates new records in the database, using the "Add" button so It's not a database connection problem).

  • 写回答

1条回答 默认 最新

  • dongzhenjian5195 2018-03-14 11:18
    关注

    Problem solved.

    When creating the JSON object in read.php,

    echo json_encode($department_arr);
    

    needs to be

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

    If don't, JSON object was created in a wrong format and Angular binding didn't work.

    Now works perfectly.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题