【问题标题】:Passing ID parameter from url to a php script using $routeParams in AngularJS?使用AngularJS中的$routeParams将ID参数从url传递到php脚本?
【发布时间】:2016-10-19 23:27:59
【问题描述】:

我喜欢将 ID 参数传递给 php,以便我可以在脚本中检索特定行的 sql 数据库。

ID 参数在 URL 中可用,例如 (http://localhost/RoutingAngularJS/index.php#/students/1)。最后一位数字 1 是数据库中的行 id,以便可以检索该行中人员的信息。

$routeParams 在控制器中用作

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

我的 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
    $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));

?>

我喜欢将 id 传递给 $student->id,现在是 ????。

谢谢

编辑:

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'];
        }
    }

?>

【问题讨论】:

  • 只需使用$_GET['id']
  • 另外,1) 从不滚动你自己的 JSON;使用json_encode。 2)你会想在then()回调中使用response.data.records
  • 你在$routeProviderwhen之间有两个点..

标签: php angularjs angular-routing routeparams


【解决方案1】:

你在这里做了一些奇怪的事情。首先,你的 PHP

Students.php - 让 readOneStudent() 返回有用的东西

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 - 以有用的状态和 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;

接下来,我将在路由配置中使用resolve 属性

$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
            });
        }
    }
 })

最后在你的控制器中

.controller('studentDetailsController', function($scope, student) {
    $scope.student = student;
})

【讨论】:

  • 我已在原帖中更新了 EDIT 中的更改。如果我按照您的建议使用解析和控制器设置,我收到 400 错误,这意味着 id 不是正确的 id。如果我按照我的 EDIT 中所示进行操作,则会出现 404 错误,找不到带有 id 的行。有什么问题?
  • @batuman 我猜你错过了评论 “假设这会返回一些有用的东西” 因为你的 readOneStudent() 方法没有返回任何东西
  • @batuman 我已经通过一些改进更新了我的答案。我尝试使用params: $routeParams 可能是错误的。请看我的新答案
  • 现在正在工作。我需要删除!在 if(!$student->readOneStudent());。谢谢
  • @batuman 不确定我是否理解。如果查询返回零行,则进行检查
【解决方案2】:

尝试在 PHP 中使用$_GET['id'] 访问带有键 id 的 GET

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    相关资源
    最近更新 更多