I have a very strange problem with MySQL and PHP.
I have into a function the below query:
Global $Linker;
$query = "INSERT INTO ".$user_type." (id) VALUES (?)";
if($stmt = mysqli_prepare($Linker->DataBase,$query)) {
mysqli_stmt_bind_param($stmt,"i",$max_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
} printf("Error: %s.
", mysqli_stmt_error($stmt));
where
$Linker is the variable that holds the database connection
and
$user_type is the table I want to insert in the database
I get the following error printed
Error: Cannot add or update a child row: a foreign key constraint fails (
std10179db/Students
, CONSTRAINTfk_Students_Users1
FOREIGN KEY (id
) REFERENCESmydb
.Users
(Table_ID
) ON DELETE NO ACTION ON UPDATE NO ACTION).
The problem is that when I run the same query directly in MySQL through command line in the server it works as expected with no errors.
I found a work around using:
$query= "SET FOREIGN_KEY_CHECKS=0";
$stmt = mysqli_prepare($Linker->DataBase,$query);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
before my query in the PHP function and another workaround would be to change my database schema but I want to know why that is happening?
I have even tried to execute the query without parameters:
$query = "INSERT INTO Students (id) VALUES (3)";
to be exactly the same with the one I put directly into the server with no success.
Any ideas?
edit:
Table USERS
CREATE TABLE `std10179db`.`Users` (
`ID` INT NOT NULL ,
`Username` VARCHAR(45) NOT NULL ,
`Password` VARCHAR(45) NOT NULL ,
`email` VARCHAR(45) NOT NULL ,
`User_Class` VARCHAR(45) NOT NULL ,
`Table_ID` INT NOT NULL ,
PRIMARY KEY (`ID`) ,
UNIQUE INDEX `Username_UNIQUE` (`Username` ASC) ,
UNIQUE INDEX `Password_UNIQUE` (`Password` ASC) ,
UNIQUE INDEX `email_UNIQUE` (`email` ASC) )
ENGINE = InnoDB;
and Table Students
CREATE TABLE `std10179db`.`Students` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`Univ_ID` VARCHAR(45) NULL ,
`Name` VARCHAR(45) NULL ,
`Surname` VARCHAR(45) NULL ,
`Telephone` VARCHAR(45) NULL ,
`Semester` INT NULL ,
`Department_id` INT UNSIGNED NULL ,
PRIMARY KEY (`id`, `Department_id`) ,
UNIQUE INDEX `idStudents_UNIQUE` (`id` ASC) ,
INDEX `fk_Students_Department1` (`Department_id` ASC) ,
CONSTRAINT `fk_Students_Department1`
FOREIGN KEY (`Department_id` )
REFERENCES `mydb`.`Department` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Students_Users1`
FOREIGN KEY (`id` )
REFERENCES `mydb`.`Users` (`Table_ID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;