无法使用 AngularJS 和 PHP 发布

Posted

技术标签:

【中文标题】无法使用 AngularJS 和 PHP 发布【英文标题】:Unable to post using AngularJS & PHP 【发布时间】:2019-01-10 14:11:09 【问题描述】:

我正在运行 AngularJS app。

我之前在本地跑过,可以发到本地服务器。

现在我在实时服务器上尝试它,我收到以下错误:

Unable to create Reservation.

每当无法发布到服务器时,此错误就会从create.php 页面发布。

有人知道我的代码有什么问题吗?

create.php 页面

  <?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once '../config/database.php';

// instantiate reservation object
include_once '../objects/reserve.php';

$database = new Database();
$db = $database->getConnection();

$reservation = new Reservation($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

// set product property values
$reservation->name = $data->name;
$reservation->eMail = $data->eMail;
$reservation->phoneNumber = $data->phoneNumber;
$reservation->colorScooter = $data->colorScooter;
$reservation->amountScooters = $data->amountScooters;
$reservation->inputDate = $data->inputDate;
$reservation->returnDate = $data->returnDate;
$reservation->category_id = $data->category_id;
$reservation->created = date('Y-m-d H:i:s');

// create the reservation
if($reservation->create())
    echo '';
        echo '"message": "Reservation was created."';
    echo '';


// if unable to create the reservation, tell the user
else
    echo '';
        echo '"message": "Unable to create Reservation."';
    echo '';

?>

编辑 02-08-18

似乎没有设置属性值。

    // set product property values
$reservation->name = $data->name;
$reservation->eMail = $data->eMail;
$reservation->phoneNumber = $data->phoneNumber;
$reservation->colorScooter = $data->colorScooter;
$reservation->amountScooters = $data->amountScooters;
$reservation->inputDate = $data->inputDate;
$reservation->returnDate = $data->returnDate;
$reservation->category_id = $data->category_id;
$reservation->created = date('Y-m-d H:i:s');

我可以在运行create.php live vs local 时看到这一点

本地

<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>24</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>27</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>28</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>29</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>30</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>31</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>32</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>33</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>34</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>35</b><br />
"message": "Unable to update reservation."

直播

 "message": "Unable to update reservation."

似乎在现场它不是在寻找属性值

在 HP 7.0 (7.0.28) 上运行

添加:

ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);

现在显示以下内容

Trying to get property of non-object in /var/www/vhosts/128/313118/webspace/httpdocs/e-citywheels.com/new/api2/reserve/create.php on line 32

编辑添加的 RESERVE.PHP

<?php
class Reservation

    // database connection and table name
    private $conn;
    private $table_name = "reservations";

    // object properties
    public $id;
    public $name;
    public $eMail;
    public $phoneNumber;
    public $colorScooter;
    public $amountScooters;
    public $inputDate;
    public $returnDate;
    public $category_name;
    public $created;

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

    // read reservations
    function read()

        // select all query
        $query = "SELECT
                    c.name as category_name, p.id, p.name, p.eMail, p.phoneNumber,  p.colorScooter, p.amountScooters, p.inputDate, p.returnDate, p.category_id, p.created
                FROM
                    " . $this->table_name . " p
                    LEFT JOIN
                        categories c
                            ON p.category_id = c.id
                ORDER BY
                    p.created DESC";

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

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

        return $stmt;
    
    // create product
    function create()

        // query to insert record
        $query = "INSERT INTO
                    " . $this->table_name . "
                SET
                    name=:name, eMail=:eMail, phoneNumber=:phoneNumber, colorScooter=:colorScooter, amountScooters=:amountScooters, inputDate=:inputDate, returnDate=:returnDate,category_id=:category_id, created=:created";

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

        // sanitize
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->eMail=htmlspecialchars(strip_tags($this->eMail));
        $this->phoneNumber=htmlspecialchars(strip_tags($this->phoneNumber));
        $this->colorScooter=htmlspecialchars(strip_tags($this->colorScooter));
        $this->amountScooters=htmlspecialchars(strip_tags($this->amountScooters));
        $this->inputDate=htmlspecialchars(strip_tags($this->inputDate));
        $this->inputDate=htmlspecialchars(strip_tags($this->returnDate));
        $this->category_id=htmlspecialchars(strip_tags($this->category_id));
        $this->created=htmlspecialchars(strip_tags($this->created));

        // bind values
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":eMail", $this->eMail);
        $stmt->bindParam(":phoneNumber", $this->phoneNumber);
        $stmt->bindParam(":colorScooter", $this->colorScooter);
        $stmt->bindParam(":amountScooters", $this->amountScooters);
        $stmt->bindParam(":inputDate", $this->inputDate);
        $stmt->bindParam(":returnDate", $this->returnDate);
        $stmt->bindParam(":category_id", $this->category_id);
        $stmt->bindParam(":created", $this->created);

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

        return false;

    
    // used when filling up the update product form
    function readOne()

        // query to read single record
        $query = "SELECT
                    c.name as category_name,  p.id, p.name, p.eMail, p.phoneNumber,  p.colorScooter, p.amountScooters, p.inputDate, p.returnDate, p.category_id, p.created
                FROM
                    " . $this->table_name . " p
                    LEFT JOIN
                        categories c
                            ON p.category_id = c.id
                WHERE
                    p.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->eMail = $row['eMail'];
        $this->phoneNumber = $row['phoneNumber'];
        $this->colorScooter = $row['colorScooter'];
        $this->amountScooters = $row['amountScooters'];
        $this->inputDate = $row['inputDate'];
        $this->returnDate = $row['returnDate'];
        $this->category_id = $row['category_id'];
        $this->category_name = $row['category_name'];
    

    // update the product
    function update()

        // update query
        $query = "UPDATE
                    " . $this->table_name . "
                SET
                    name = :name,
                    eMail = :eMail,
                    phoneNumber = :phoneNumber,
                    colorScooter = :colorScooter
                    amountScooters = :amountScooters,
                    inputDate = :inputDate,
                    returnDate = :returnDate,
                    category_id = :category_id
                WHERE
                    id = :id";

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

        // sanitize
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->eMail=htmlspecialchars(strip_tags($this->eMail));
        $this->phoneNumber=htmlspecialchars(strip_tags($this->phoneNumber));
        $this->colorScooter=htmlspecialchars(strip_tags($this->colorScooter));
        $this->amountScooters=htmlspecialchars(strip_tags($this->amountScooters));
        $this->inputDate=htmlspecialchars(strip_tags($this->inputDate));
        $this->inputDate=htmlspecialchars(strip_tags($this->returnDate));
        $this->category_id=htmlspecialchars(strip_tags($this->category_id));
        $this->id=htmlspecialchars(strip_tags($this->id));





        // bind new values
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":eMail", $this->eMail);
        $stmt->bindParam(":phoneNumber", $this->phoneNumber);
        $stmt->bindParam(":colorScooter", $this->colorScooter);
        $stmt->bindParam(":amountScooters", $this->amountScooters);
        $stmt->bindParam(":inputDate", $this->inputDate);
        $stmt->bindParam(":returnDate", $this->returnDate);
        $stmt->bindParam(':category_id', $this->category_id);
        $stmt->bindParam(':id', $this->id);

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

        return false;
    

    // delete the product
    function delete()

        // delete query
        $query = "DELETE FROM " . $this->table_name . " WHERE 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;

    

    // search products
    function search($keywords)

        // select all query
        $query = "SELECT
                    c.name as category_name, p.id, p.name, p.eMail, p.phoneNumber,  p.colorScooter, p.amountScooters, p.inputDate, p.returnDate, p.category_id, p.created
                FROM
                    " . $this->table_name . " p
                    LEFT JOIN
                        categories c
                            ON p.category_id = c.id
                WHERE
                    p.name LIKE ? OR p.description LIKE ? OR c.name LIKE ?
                ORDER BY
                    p.created DESC";

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

        // sanitize
        $keywords=htmlspecialchars(strip_tags($keywords));
        $keywords = "%$keywords%";

        // bind
        $stmt->bindParam(1, $keywords);
        $stmt->bindParam(2, $keywords);
        $stmt->bindParam(3, $keywords);

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

        return $stmt;
    

    // read products with pagination
    public function readPaging($from_record_num, $records_per_page)

        // select query
        $query = "SELECT
                    c.name as category_name, p.id, p.name, p.eMail, p.phoneNumber,  p.colorScooter, p.amountScooters, p.inputDate, p.returnDate, p.category_id, p.created
                FROM
                    " . $this->table_name . " p
                    LEFT JOIN
                        categories c
                            ON p.category_id = c.id
                ORDER BY p.created DESC
                LIMIT ?, ?";

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

        // bind variable values
        $stmt->bindParam(1, $from_record_num, PDO::PARAM_INT);
        $stmt->bindParam(2, $records_per_page, PDO::PARAM_INT);

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

        // return values from database
        return $stmt;
    

    // used for paging products
    public function count()
        $query = "SELECT COUNT(*) as total_rows FROM " . $this->table_name . "";

        $stmt = $this->conn->prepare( $query );
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row['total_rows'];
    


添加于 2018 年 8 月 11 日

添加var_dump($product); 结果表明变量$product 确实返回了表,而$data 实际上是问题所在。

var_dump($product);的结果

 ["table_name":"Product":private]=>
  string(8) "products"
  ["id"]=>
  NULL
  ["name"]=>
  NULL
  ["email"]=>
  NULL
  ["phone"]=>
  NULL
  ["amount"]=>
  NULL
  ["description"]=>
  NULL
  ["pickup"]=>
  NULL
  ["back"]=>
  NULL
  ["category_id"]=>
  NULL
  ["category_name"]=>
  NULL
  ["created"]=>
  NULL

当前状态

如果我打开 create.php 文件,它会创建一个产品,但如果我使用该表单,我会收到错误无法创建产品。

此外,当我打开 create.php 文件时,我收到以下错误消息:

<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>37</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>38</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>39</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>40</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>41</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>42</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>43</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>44</b><br />

似乎找不到“名称”属性。

我知道是什么导致了这个问题,

工厂

// create product
factory.createProduct = function($scope)
    return $http(
        method: 'POST',
        data: 
            'name' : $scope.name,
            'email' : $scope.email,
            'phone' : $scope.phone,
            'amount' : $scope.amount,
            'description' : $scope.description,
            'pickup' : $scope.pickup,
            'back' : $scope.back,
            'category_id' : 1
        ,
        url: 'http://localhost/api/product/create.php'

    );
;

我的控制器

// create new product
$scope.createProduct = function()

    productsFactory.createProduct($scope).then(function successCallback(response)

        // tell the user new product was created
        $scope.showToast(response.data.message);

        // refresh the list
        $scope.readProducts();

        // close dialog
        $scope.cancel();

        // remove form values
        $scope.clearProductForm();

    , function errorCallback(response)
        $scope.showToast("Unable to create record.");
    );

product.php

    // create product
function create()

    // query to insert record
    // $query = "INSERT INTO " . $this->table_name . 
    // "(name, email, phone, amount, description, pickup, back, created, modified)" .
    // " VALUES(:name, :email, :phone, :amount, :description, :pickup, :back, :created, :modified)";

    $query = "INSERT INTO
                " . $this->table_name . "
            SET
                name=:name, email=:email, phone=:phone, amount=:amount, description=:description, pickup=:pickup, back=:back, category_id=:category_id, created=:created";

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

    // sanitize
    $this->name=htmlspecialchars(strip_tags($this->name));
    $this->email=htmlspecialchars(strip_tags($this->email));
    $this->phone=htmlspecialchars(strip_tags($this->phone));
    $this->amount=htmlspecialchars(strip_tags($this->amount));
    $this->description=htmlspecialchars(strip_tags($this->description));
    $this->pickup=htmlspecialchars(strip_tags($this->pickup));
    $this->back=htmlspecialchars(strip_tags($this->back));
    $this->category_id=htmlspecialchars(strip_tags($this->category_id));
    $this->created=htmlspecialchars(strip_tags($this->created));

    // bind values
    $stmt->bindParam(":name", $this->name);
    $stmt->bindParam(":email", $this->email);
    $stmt->bindParam(":phone", $this->phone);
    $stmt->bindParam(":amount", $this->amount);
    $stmt->bindParam(":description", $this->description);
    $stmt->bindParam(":pickup", $this->pickup);
    $stmt->bindParam(":back", $this->back);
    $stmt->bindParam(":category_id", $this->category_id);
    $stmt->bindParam(":created", $this->created);

    // 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");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once '../config/database.php';

// instantiate product object
include_once '../objects/product.php';

$database = new Database();
$db = $database->getConnection();

$product = new Product($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

echo $data;

var_dump($data);

var_dump($product);


print_r($data);

var_dump($product->name);

// set product property values
$product->name = $data->name;
$product->email = $data->email;
$product->phone = $data->phone;
$product->amount = $data->amount;
$product->description = $data->description;
$product->pickup = $data->pickup;
$product->back = $data->back;
$product->category_id = $data->category_id;
$product->created = date('Y-m-d H:i:s');



var_dump($product->name);
var_dump($data->name);

echo is_array($product->name) ? 'Array' : 'not an Array';

echo json_last_error();
// create the product
if($product->create())
    echo '';
        echo '"message": "Product was created."';
    echo '';


// if unable to create the product, tell the user
else
    echo '';
        echo '"message": "Unable to create product."';

    echo '';



?>

2018 年 8 月 12 日更新

运行 createproduct() 它执行 postcreate.php

我用谷歌浏览器的检查器网络标签检查了它。

name: "test", email: "test", phone: "test", amount: "test", description: "test", pickup: "test",…
amount
:
"test"
back
:
"test"
description
:
"test"
email
:
"test"
name
:
"test"
phone
:
"test"
pickup
:
"test"

它还返回代码:200

根据link的意思是:

200 正常 此响应码表示请求成功。

201 已创建 这表示请求成功并创建了资源。用于确认 PUT 或 POST 请求是否成功。

似乎没有创建新资源,也没有发布任何内容。

【问题讨论】:

即使发送了所有参数,您是否也遇到同样的错误? 是的,如果我输入所有参数,我会收到错误消息,请查看我已在顶部超链接我的应用程序。 错误仅在$reservation-&gt;created = date('Y-m-d H:i:s'); 行是吗?你也可以发布reserve.php吗? @MadhanVaradhodiyil 我已经添加了!不,它似乎没有调用任何属性 无法重现问题。您的代码对我有用。你试过打印$data吗? 【参考方案1】:

为什么要使用 php://input?您是否有理由不使用 $_POST 访问发布的数据?如果 POST 请求命中 php,则创建全局关联数组 $_POST。每个索引都将匹配表单中的一个名称属性并包含其值。

显示的错误可能来自这种方法,因为 php://input 可以是任何东西,所以 $data 可以是。如果是这种情况,您尝试从实际上不是对象的对象中分配值 ($reservation->name = $data->name;)。

// get posted data
$data = json_decode(file_get_contents("php://input"));

// set product property values
$reservation->name = $data->name;
$reservation->eMail = $data->eMail;
$reservation->phoneNumber = $data->phoneNumber;
$reservation->colorScooter = $data->colorScooter;
$reservation->amountScooters = $data->amountScooters;
$reservation->inputDate = $data->inputDate;
$reservation->returnDate = $data->returnDate;
$reservation->category_id = $data->category_id;
$reservation->created = date('Y-m-d H:i:s');

明确 $data 的数据类型并确保它无论如何都保持不变。 (尝试使用 var_dump 代替 echo 或 print_r,获得更多信息)

【讨论】:

感谢您发布答案,确保每个 $data 都在实际对象上的最佳方法是什么。 你能举个例子说明我应该如何使用 $_POST 吗? 给你所有的表单域一个名字属性,然后用一个后请求和一个 var_dump($_POST) 来点击你的入口点;您将看到它的索引与您的名称属性匹配的关联数组,例如,如果您有这样的输入 您可以使用 echo $_POST["username "];编辑:要使用您已经编码的结构节省一些工作,您可以将 $_POST 数组映射到与您现有结构匹配的对象。 我在哪里放置 $_POST ?在create.php? 是的,在 create.php 上方的“// 获取发布的数据” print_r($_POST);后跟一个 exit();停止进一步执行【参考方案2】:

确保在进行任何事务之前检查所有变量值和数组值。您可以在任何时候使用

验证它们
isset() 

is_array()

因此,您将清楚地知道哪个没有设置在正确的位置。因此,您将能够非常清楚地跟踪它。否则你会浪费时间去追查问题。

【讨论】:

会试一试,奇怪的是我已经根据教程构建了这个应用程序。我重复了这些步骤,有时有效,有时无效。【参考方案3】:
    检查您在file_get_contents("php://input") (var_dump) 上获得了什么 在 factory.createProduct 你有url: 'http://localhost/api/product/create.php'。这是你想要的吗?从远程调用本地主机?你不使用'/api/product/create.php'吗?

【讨论】:

您好,感谢您的回复!使用 URL http://localhost/api/product/create.php/api/product/create.php 并没有什么不同。我试过var_dump it and it returnsstring(0) ""

以上是关于无法使用 AngularJS 和 PHP 发布的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 PHP MySQL 更新数据库,其中数据来自 AngularJS1.2 服务

AngularJS 与 PHP:为啥我的应用程序无法保存输入文本发送的字符串?

无法使AngularJS路由工作

如何在 AngularJS 部分文件中使用 php (wordpress) 函数?

angular的post传参后台php无法接收

Highcharts:无法使用AngularJS读取未定义的属性'parentGroup'