在输入更改时,似乎无法通过PHP在服务器上运行SQL查询。有人可以看看我的代码并为我提供帮助吗?
负责处理对服务器的http请求的服务:
import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class CrudService {
public url = 'http://localhost/web_api/';
constructor(private http: HttpClient) { }
registerNormal(data)
{
return this.http.post(this.url + 'registerNormal.php', data);
}
accountExists(data)
{
return this.http.get(this.url + 'existingAccounts.php', data);
}
}
负责传递数据的功能
CheckAccountAvailability(values)
{
const registerNormalFormData = new FormData();
registerNormalFormData.append('username', values.username);
if (this.registerNormal.get('username').valid)
this.crudService.accountExists(registerNormalFormData).subscribe(result => {console.log(result)});
}
PHP文件运行良好,因为我已经用邮递员对其进行了测试,并且registerNormal()
函数也运行良好。
我似乎没有确切指出问题所在。
非常感谢!
编辑:
下面是调用该函数的组件的html代码。该函数被调用,但是由angular返回的结果为NULL
,但是PHP API使用postman可以很好地返回结果
<input matInput placeholder="User Name" formControlName="username" required (input)="CheckAccountAvailability(registerNormal.value)">
编辑2:
以下是existingAccounts.php的php代码
<?php
if ($_GET)
{
// include database connection
include 'config/database.php';
try
{
// check if account exists in database
$q_normalAccountExists = "SELECT * FROM normal_accounts WHERE username=:username";
// $q_bandAccountExists = "SELECT * FROM band_accounts WHERE username=:username";
// prepare queries to check if accounts exist in database
$checkNormalAccount = $con->prepare($q_normalAccountExists);
// $checkBandAccount = $con->prepare($q_bandAccountExists);
// GET username
$username = $_GET['username'];
// bind parameters to check if username exists in database
$checkNormalAccount->bindParam(':username', $username);
// $checkBandAccount->bindParam(':username', $username);
// execute username exists in database query
$checkNormalAccount->execute();
// $checkBandAccount->execute();
if ($checkNormalAccount->rowCount() == 0/* && $checkBandAccount->rowCount() == 0*/)
{
echo json_encode(array('result'=>false));
}
else
{
echo json_encode(array('result'=>true));
}
}
// show error
catch(PDOException $exception)
{
die('ERROR: ' . $exception->getMessage());
}
}
?>
编辑3:
似乎将GET请求更改为POST请求可以解决此问题。但是,谁能告诉我为什么GET请求无法正常工作?