I am new to PHP and SQL. I simply want to register a user after a team of users has been created. Tables that i have used -
team
idTeam int(11) PK + AI
teamName varchar(25)
user
idUser int(11) PK + AI
name varchar(30)
username varchar(30)
password varchar(30)
team int(11) FK
I have used the following code-
<?php
session_start();
include('conn.php');
$name=$_POST['name'];
$team=$_POST['team'];
$username=$_POST['username'];
$password=$_POST['password'];
$qry="SELECT * FROM team WHERE idTeam='$team";
if(mysqli_query($con,$qry)){
mysqli_query("INSERT INTO user(name, team, username, password)VALUES('$name', '$team', '$username', '$password')");
header("location: add_user.php?remarks=success");
mysqli_close($con);
}
else
mysqli_error($con);
?>
i used to get error- Mysql error 1452 - Cannot add or update a child row: a foreign key constraint failsMysql error 1452 - Cannot add or update a child row: a foreign key constraint fails
Example - I have pre-entered the contents of team table-
idTeam - teamName
1 Arsenal
2 Chelsea
3 Liverpool
Now if i want to add a user then I would add him by entering in user table-
idUser team name username password
1 2 abc root pass
So here i am unable to figure out what query should i use in PHP code?
在团队表中必须存在一条记录,该记录对应于传递给$team
的值
Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table.
It will reject any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.
https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
There is a single quotation within your first sql query near idTeam='$team. idTeam is integer type. So it need not within single quotation. Make sure that you are passing value for $team variable that is exist in team table. Try following code.
$name=$_POST['name'];
$team=$_POST['team'];
$username=$_POST['username'];
$password=$_POST['password'];
$qry="SELECT * FROM team WHERE idTeam=$team";
$result = mysqli_query($qry);
$num_rows = mysqli_num_rows($result);
if($num_rows > 0){
mysqli_query("INSERT INTO user(name, team, username, password)VALUES('$name', $team, '$username', '$password')");
}else{
echo "Team is not valid!!!";
}
mysqli_close($con);
header("location: add_user.php?remarks=success");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.