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).