Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 电文:";的Http失败响应http://localhost/post.php: 0未知错误“&;邮递http://localhost/post.php net::ERR_失败_Javascript_Php_Mysql_Angular_Typescript - Fatal编程技术网

Javascript 电文:";的Http失败响应http://localhost/post.php: 0未知错误“&;邮递http://localhost/post.php net::ERR_失败

Javascript 电文:";的Http失败响应http://localhost/post.php: 0未知错误“&;邮递http://localhost/post.php net::ERR_失败,javascript,php,mysql,angular,typescript,Javascript,Php,Mysql,Angular,Typescript,我正在尝试将数据添加到数据库中,我没有看到错误,感觉卡住了。 作为PHP和Angular的初级用户,请通过xampp和Angular 8使用PHP 我们可以在php文件中为post和get方法生成2个文件吗 应用程序组件.ts import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { FormBuilder, FormGroup, F

我正在尝试将数据添加到数据库中,我没有看到错误,感觉卡住了。 作为PHP和Angular的初级用户,请通过xampp和Angular 8使用PHP

我们可以在php文件中为post和get方法生成2个文件吗

应用程序组件.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  getUrl: string = 'http://localhost/test.php';
  postUrl: string = 'http://localhost/post.php';
  product = [];
  reactiveForm = new FormGroup({
    name: new FormControl(),
    lastname: new FormControl(),
    city: new FormControl(),
  });

  constructor(private httpClient: HttpClient, private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.getMethod();
  }

  postMethod() {
    let myFormData = new FormData();
    myFormData.append('name', this.reactiveForm.value.name);
    myFormData.append('lastname', this.reactiveForm.value.lastname);
    myFormData.append('city', this.reactiveForm.value.city);

    return this.httpClient.post(this.postUrl, myFormData).subscribe(
      (response) => console.log(response),
      (error) => console.log(error)
    );
  }

  onSubmit() {
    console.log('resulat', this.reactiveForm.value);
    this.postMethod();
  };

  getMethod() {
    this.httpClient.get(this.getUrl).subscribe(data => {
      this.product.push(data);
    }, error => console.error(error));
  };
}
app.component.html

   <form [formGroup]="reactiveForm" (ngSubmit)="onSubmit()">

    <div class="form-group">
      <label class="label">Name</label>
      <input class="input" type="text" formControlName="name"><br>
    </div>

    <div class="form-group">
      <label class="label">LastName</label>
      <input class="input" type="text" formControlName="lastname"><br>
    </div>

    <div class="form-group">
      <label class="label">city</label>
      <input class="input" type="text" formControlName="city"><br>
    </div>

    <button type="submit">Submit</button>

  </form>

名称

姓氏
城市
提交
post.php

我已经为Get方法解决了Access Control Allow Origin错误,但是它返回了为什么

<?php

    header('Access-Control-Allow-Origin: *'); 
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

    $postdata = file_get_contents("php://input", true);

    $servername = "localhost";
    $username   = "root";
    $password   = "";
    $dbname     = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    //echo "Connected successfully";

    if(isset($_POST['name'])) $name=$_POST['name'];
     else      $name="";

    if(isset($_POST['lastname'])) $name=$_POST['lastname'];
     else      $lastname="";

    if(isset($_POST['city'])) $name=$_POST['city'];
     else      $city="";

     // Add User
     $sql = "INSERT INTO `test_1` (`id`, `name`, `lastname`, `city`) VALUES ('', '$name', '$lastname', '$city')";

    if ($conn->query($sql) === TRUE) {
        $myJSON = json_encode("New user created successfully");
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    mysqli_close($conn);
?>

首先,我建议您阅读下面的评论,这里有一些关于SQL注入和漏洞的非常重要的答案

第二,回答你的问题。开始读取错误消息。错误消息显示第35行未定义$lastname。这意味着在查询中使用了变量$lastname,但您从未在代码中创建过该变量

如果您阅读代码,您将看到以下内容

if(isset($_POST['lastname'])) $name=$_POST['lastname'];
     else      $lastname="";

    if(isset($_POST['city'])) $name=$_POST['city'];
     else      $city="";
如果设置了post lastname,则覆盖
$name
,否则将
$lastname
设置为空,城市对账单也是如此。也就是说,只有在变量lastname未发布时才创建它

如果您使用的是PHP7+,那么实际上可以使用
操作符(空合并)。这将为您完成isset,您可以这样编写代码

$name = $_POST['name'] ?? '';
$lastname = $_POST['lastname'] ?? '';
$city = $_POST['city'] ?? '';
如果您仍然使用PHP5+,那么您的代码很好,但就我个人而言,我更喜欢使用三元运算符,这会再次减少出现问题的机会

$name = true === isset($_POST['name']) ? $_POST['name'] : '';
现在什么是非常重要的,这就是为什么我说阅读评论。现在有人可以在你的页面上发布值,比如

$_POST['lastname'] = '\'; DROP TABLE test_1; \'//';
如果发布正确且您的权限不正确(不是xss执行专家),它将删除该表。如果删除表是您最不担心的事情,那么提取数据才是真正的危险所在

因此,转义查询参数总是明智的,最好使用mysqli或PDO的机制,通过使用准备好的语句来转义查询参数

在mysqli中,您的代码大致如下

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
否则,您至少可以使用本机mysqli函数

mysqli_real_escape_string ( mysqli $link , string $escapestr ) : string



// Add User
$sql = "INSERT INTO `test_1` (`id`, `name`, `lastname`, `city`) VALUES ('', '" . mysqli_real_escape_string($con, $name) . "', '" . mysqli_real_escape_string($con, $lastname) . "', '" . mysqli_real_escape_string($con, $city) . "')";
此外,如果您的ID是自动递增的,则不应将其添加到查询中,或者使用mysql关键字
DEFAULT
作为值,而不是空字符串

最后:在转义您的输入之后,最好验证它是否是您想要的,例如,从理论上讲,名称不应该只包含数字

更多关于准备好的声明

关于PHP操作符的更多信息(空合并和三元)


出于个人考虑,请始终对if语句使用
{}
,使其更具可读性,并防止第二行为什么不执行的错误?

警告:您的代码容易受到SQL注入攻击。您应该使用参数化查询和准备好的语句来帮助防止攻击者使用恶意输入值破坏您的数据库。给出了风险的解释,以及如何使用PHP/mysqli安全地编写查询的一些示例。切勿将未初始化的数据直接插入SQL。按照现在编写代码的方式,有人很容易窃取、错误地更改甚至删除您的数据。还包含使用mysqliAlso编写安全SQL的好例子,因此永远不要让web应用以root用户身份登录数据库。Root可以做任何它喜欢的事情,所以除了SQL注入漏洞之外,这只会让您的数据库成为黑客们的一本打开的书。而是专门为此应用程序创建一个单独的用户帐户,该应用程序仅具有正常工作所需的权限。在开发或测试期间,甚至不要将根帐户用作快捷方式,因为您还需要测试您的帐户权限-否则,当您上线时,可能会出现与用户帐户设置相关的意外错误。提示:当前,PHP在成功时返回JSON,在出现错误时返回HTML。这对于试图读取响应的客户机代码来说是令人困惑和恼火的,因为它事先不知道如何解析响应。要么坚持总是给出JSON响应,要么总是给出HTML/文本响应
$name=$\u POST['city']看起来不对,你不觉得吗?应该是
$lastname=$\u POST['city']
$city=$\u POST['city']我期待。请务必仔细检查您的工作!