大家好,为什么我的数据在db中保存两次?如果我提交表单,表单数据将被保存,但它在db中创建另一个empety行也为什么?
结果如下:
名称 - 用户名 - 电子邮件 - 号码
- - - -
我的用户服务
import {Injectable} from "@angular/core";
import {User} from "./user";
import {Http} from "@angular/http";
import "rxjs";
import { Observable } from "rxjs"
@Injectable()
export class UserService {
constructor(private _http: Http) {
}
create(user) {
return this._http.post('http://localhost/api/create.php', user).map(()=>"")
}
user.component.ts
import {Component, OnInit} from "@angular/core";
import {User} from "./user";
import {UserService} from "./user.service";
import {isNumber} from "util";
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
// users: Array<User> = [
// new User(1, 'fist', 'last', 'aa@aa.com'),
// new User(2, 'second', '2last', 'aa@aa.com'),
// new User(3, 'third', '3last', 'aa@aa.com')
//
// ];
users: Array<User>;
constructor(private _userService: UserService) {
}
ngOnInit() {
this.getUsers();
// this.destroy();
}
create(user) {
//console.log(user);
this._userService.create(user).subscribe(() => this.getUsers())
}
destroy(id) {
this._userService.ndelete(id.id).subscribe(() => this.getUsers())
}
// update(users: any) {
// const i = this.users.indexOf(users.original);
// this.users[i] = users.edited;
//}
getUsers() {
this._userService.getUsers()
.subscribe(users => {
this.users = users
});
}
}
这是我的子组件,它将数据发送到父
用户-new.component.ts
import {Component, OnInit, Output, EventEmitter} from '@angular/core';
import {User} from "../user";
@Component({
selector: 'app-user-new',
templateUrl: './user-new.component.html',
styleUrls: ['./user-new.component.css']
})
export class UserNewComponent implements OnInit {
newUser = new User();
@Output() createNewUserEvent = new EventEmitter();
constructor() { }
ngOnInit() {
}
create(){
this.createNewUserEvent.emit(this.newUser);
//this.newUser = new User;
}
}
及其形式
<h3>user new component</h3>
<form (submit)= "create()">
<input type="text" name="name" [(ngModel)]="newUser.name">
<input type="text" name="username" [(ngModel)]="newUser.username">
<input type="text" name="email" [(ngModel)]="newUser.email">
<input type="text" name="phone" [(ngModel)]="newUser.phone">
<input type="submit">
</form>
这里是与mysql数据库交互的php文件
include ("db.class.php");
$conn = new Db();
$data = json_decode(file_get_contents("php://input"));
$sql = "insert into users set
name= '$data->name',
username= '$data->username',
email= '$data->email',
phone= '$data->phone'
";
$stmt = $conn->conn->prepare($sql);
$stmt->execute();
$conn->conn = null;
//end
答案 0 :(得分:0)
我无法弄清楚错误,但您可以使用if(!empty(value))来阻止将空值输入数据库。
if(!empty($data)){ $sql = "insert into users set
name= '$data->name',
username= '$data->username',
email= '$data->email',
phone= '$data->phone'"; }
这将阻止插入空的数据库行。