1

I like to pass ID parameter to php so that I can retrieve a particular row of sql database inside the script.

The ID parameter is available in URL, for example (http://localhost/RoutingAngularJS/index.php#/students/1). That last digit 1 is the row id in database so that information of a person in that row can be retrieved.

$routeParams is used in controller as

var app = angular.module("Demo", ["ngRoute"])
             .config(function($routeProvider){
             $routeProvider
             .
             .when("/students/:id", {
                 templateUrl:"Templates/studentDetails.html",
                 controller:"studentDetailsController"
             })
        })
          .controller("studentDetailsController", function ($scope, $http, $routeParams) {
                 $http({
                     url:"api/ReadOneStudent.php",
                        params:{id:$routeParams.id},
                     method: "get"

                 }).then(function(response){
                    $scope.student = response.records;
                 })               
            });

My ReadOneStudent.php is

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
// include database and object files  
    include_once 'database.php'; 
    include_once 'Students.php';

    // instantiate database and product object 
    $database = new Database(); 
    $db = $database->getConnection();

    // initialize object
    $student = new Students($db);

    // get id of product to be edited
    //$data = json_decode(file_get_contents("php://input"));     

    // set ID property of product to be edited
    $student->id = ????;

    // read the details of product to be edited
    $student->readOneStudent();

    // create array
    $student_arr[] = array(
        "id" =>  $student->id,
        "name" => $student->name,
        "gender" => $student->gender,
        "city" => $product->city
    );
    echo '{"records":[' . $student_arr . ']}'; 
    // make it json format
    //print_r(json_encode($student_arr));

?>

I like to pass id to $student->id, now is with ????.

Thanks

EDIT:

var app = angular.module("Demo", ["ngRoute"])
                 .config(function($routeProvider){
                 $routeProvider
                 .
                 .when("/students/:id", {
                     templateUrl:"Templates/studentDetails.html",
                     controller:"studentDetailsController"
                 })
            })
              .controller("studentDetailsController", function ($scope, $http, $routeParams) {
                     $http({
                         url:"api/ReadOneStudent.php",
                            params:$routeParams,
                         method: "get"

                     }).then(function(response){
                        $scope.student = response.data;
                     })               
                });

ReadOneStudent.php

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
// include database and object files  
    include_once 'database.php'; 
    include_once 'Students.php';

    // instantiate database and product object 
    $database = new Database(); 
    $db = $database->getConnection();

    // initialize object
    $student = new Students($db);

    // get id of product to be edited
    //$data = json_decode(file_get_contents("php://input"));     

    // set ID property of product to be edited
    if (!isset($_GET['id'])) {
        http_response_code(400); // bad request
        exit;
    }

    $student->id = $_GET['id'];

    // read the details of product to be edited
    $found = $student->readOneStudent(); // assuming this returns something useful
    if (!$found) {
        http_response_code(404);
        exit;
    }

    // create array
    // Seeing as this is called "read ONE student", why return an array?
    header('Content-type: application/json');
    echo json_encode([
        'id'     => $student->id,
        'name'   => $student->name,
        'gender' => $student->gender,
        'city'   => $student->city
    ]); // maybe you can even just use json_encode($student)
    exit;
    // make it json format
    //print_r(json_encode($student_arr));

?>

Students.php

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
    class Students{ 
        // database connection and table name 
        private $conn; 
        private $table_name = "tblStudents"; 

        // object properties 
        public $id; 
        public $name; 
        public $gender; 
        public $city; 

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

            // query to read single record
            $query = "SELECT 
                        id, name, gender, city  
                      FROM 
                        " . $this->table_name . "
                      WHERE 
                        id = ?
                      LIMIT 
                        0,1";

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

            // bind id of product to be updated
            $stmt->bindParam(1, $this->id);

            // execute query
            $stmt->execute();

            // get retrieved row
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            // set values to object properties
            $this->name = $row['name'];
            $this->gender = $row['gender'];
            $this->city = $row['city'];
        }
    }

?>
3
  • Simply use $_GET['id'] Commented Oct 19, 2016 at 23:52
  • Also, 1) NEVER roll your own JSON; use json_encode. 2) You'll want to use response.data.records in the then() callback Commented Oct 19, 2016 at 23:54
  • You have two dots .. between $routeProvider and when Commented Oct 20, 2016 at 4:00

2 Answers 2

1

There's some strange things you're doing here. First, your PHP

Students.php - make readOneStudent() return something useful

if (!$row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    return false;
}

// set values to object properties
$this->name = $row['name'];
$this->gender = $row['gender'];
$this->city = $row['city'];

$stmt->closeCursor();
return true;

ReadOneStudent.php - respond with useful statuses and JSON

if (!isset($_GET['id'])) {
    http_response_code(400); // bad request
    exit;
}

$student->id = $_GET['id'];
if (!$student->readOneStudent()) {
    http_response_code(404);
    exit;
}

// Seeing as this is called "read ONE student", why return an array?
header('Content-type: application/json');
echo json_encode([
    'id'     => $student->id,
    'name'   => $student->name,
    'gender' => $student->gender,
    'city'   => $student->city
]); // maybe you can even just use json_encode($student)
exit;

Next, I'd use the resolve property in the route configuration

$routeProvider.when("/students/:id", {
    templateUrl: "Templates/studentDetails.html",
    controller:"studentDetailsController",
    resolve: {
        student: function($routeParams, $http) {
            return $http.get('api/ReadOneStudent.php', {
                params: {id: $routeParams.id}
            }).then(function(response) {
                return response.data
            });
        }
    }
 })

and finally in your controller

.controller('studentDetailsController', function($scope, student) {
    $scope.student = student;
})
Sign up to request clarification or add additional context in comments.

5 Comments

I have updated changes in EDIT in the original post. If I used resolve as you suggested and controller setting, I got 400 error, that means id is no proper id. If I do as shown in my EDIT, I have 404 error, can't find the row with id. What could be wrong?
@batuman I guess you missed the comment "assuming this returns something useful" as your readOneStudent() method doesn't return anything
@batuman I've updated my answer with some improvements. I may have been wrong to try and use params: $routeParams. Please see my new answer
Now is working. I need to delete ! at if(!$student->readOneStudent());. Thanks
@batuman not sure I understand that. That check is there in case the query returns zero rows
1

Try to use $_GET['id'] to get access to the GET with key id in PHP

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.