It is not inserting data into a Table - php

I have some php code below that adds data into 2 tables, one known as the "Image Table" and another known as the "Image_Question" Table. The problem I'm facing is while it inserts into the "Image" Table, it doesn't insert any data into the "Image_Question" Table.
Now I know the PHP code is fine because it used to be able to insert the data into both tables with no problems.
Only after I added indexes and foreign keys to my table this problem started occurring.
Below is the PHP code that inserts the data into both tables:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],"ImageFiles/" . $_FILES["fileImage"]["name"]);
$imagesql = "INSERT INTO Image (ImageFile) VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
//Don't pass data directly to bind_param store it in a variable
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastID = $mysqli->insert_id;
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId) VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err imagequestion";
}
$qnum = (int)$_POST['numimage'];
$insertimagequestion->bind_param("isi",$lastID, $sessid, $qnum);
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$insertimagequestion->execute();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
Here's the output of SHOW CREATE TABLE for the Image Table, Image_Question Table and also the Question Table as the Image_Question Table relates to that table:
Image Table:
CREATE TABLE `Image` (
`ImageId` int(10) NOT NULL AUTO_INCREMENT,
`ImageFile` varchar(250) NOT NULL,
PRIMARY KEY (`ImageId`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8
Image_Question Table:
CREATE TABLE `Image_Question` (
`ImageQuestionId` int(10) NOT NULL AUTO_INCREMENT,
`ImageId` int(10) NOT NULL,
`SessionId` varchar(10) NOT NULL,
`QuestionId` int(5) NOT NULL,
PRIMARY KEY (`ImageQuestionId`),
KEY `FK_QuestionImage` (`ImageId`),
KEY `questionId` (`QuestionId`),
KEY `sessionId` (`SessionId`),
CONSTRAINT `FK_Image_Question` FOREIGN KEY (`SessionId`) REFERENCES `Question` (`SessionId`) ON DELETE CASCADE,
CONSTRAINT `FK_question` FOREIGN KEY (`QuestionId`) REFERENCES `Question` (`QuestionId`) ON DELETE CASCADE,
CONSTRAINT `FK_QuestionImage` FOREIGN KEY (`ImageId`) REFERENCES `Image` (`ImageId`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8
Question Table:
CREATE TABLE `Question` (
`SessionId` varchar(10) NOT NULL DEFAULT '',
`QuestionId` int(5) NOT NULL,
`QuestionContent` varchar(5000) NOT NULL,
`NoofAnswers` int(2) NOT NULL,
`AnswerId` int(10) NOT NULL AUTO_INCREMENT,
`ReplyId` varchar(2) NOT NULL,
`QuestionMarks` int(4) NOT NULL,
`OptionId` varchar(3) NOT NULL,
PRIMARY KEY (`SessionId`,`QuestionId`),
KEY `FK_Option_Table` (`OptionId`),
KEY `FK_IndividualQuestion` (`QuestionId`),
KEY `FK_Reply` (`ReplyId`),
KEY `FK_AnswerId` (`AnswerId`)
) ENGINE=InnoDB AUTO_INCREMENT=76 DEFAULT CHARSET=utf8

$img = 'ImageFiles/'.$_FILES['fileImage']['name'];
$insert->bind_param("s",$img);
Use this instead of
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];

Related

no entry into parent table but "0" or "blank" insert into FK in child table

Hi guys I am trying to solve one problem with inserting data to Parent - Child tables. Tables below and also ERR diagram show a structure and PK/FK keys. I am inserting data from webform and PHP is used to capture data and pass it to the database.
Fields in mainTable - F_Name, L_Name and Email are just input textfields,
fields in college tables are checkboxes.
Imagine that one teacher can teach at one, two or three colleges where he checks the checkbox for each college/school where he is teaching. But if he teaches only at one college there is when my problem comes. As all of the "college" tables are linked to "Teacher" with PK/FK.
My question is, is there any way how to store auto generated College ID's if for example teacher is teaching only at one college. At the moment with my PHP it fails and I don't know how to fix it.
I have a example of my PHP under the Schema structure. Just a small note that connection to database works properly.
If this or similar was already asked I do appologize.
Thanks for any tips.
-------------------------------------------------------
-- Schema test
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `test` DEFAULT CHARACTER SET latin1 ;
USE `test` ;
-- -----------------------------------------------------
-- Table `test`.`CollegeA`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`CollegeA` (
`CollegeAID` INT(11) NOT NULL AUTO_INCREMENT,
`SchoolA` VARCHAR(45) NOT NULL,
`SchoolB` VARCHAR(45) NOT NULL,
`SchoolC` VARCHAR(45) NOT NULL,
PRIMARY KEY (`CollegeAID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `test`.`CollegeB`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`CollegeB` (
`CollegeBID` INT(11) NOT NULL AUTO_INCREMENT,
`School1` VARCHAR(45) NOT NULL,
`School2` VARCHAR(45) NOT NULL,
`School3` VARCHAR(45) NOT NULL,
PRIMARY KEY (`CollegeBID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `test`.`CollegeC`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`CollegeC` (
`CollegeCID` INT(11) NOT NULL AUTO_INCREMENT,
`School11` VARCHAR(45) NOT NULL,
`School22` VARCHAR(45) NOT NULL,
`School33` VARCHAR(45) NOT NULL,
PRIMARY KEY (`CollegeCID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
-- -----------------------------------------------------
-- Table `test`.`Teacher`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`Teacher` (
`TeacherId` INT(11) NOT NULL AUTO_INCREMENT,
`F_name` VARCHAR(45) NOT NULL,
`L_name` VARCHAR(45) NOT NULL,
`Email` VARCHAR(45) NOT NULL,
`CollegeAID` INT(11) NOT NULL,
`CollegeBID` INT(11) NOT NULL,
`CollegeCID` INT(11) NOT NULL,
PRIMARY KEY (`MainId`),
INDEX `CollegeAID_idx` (`CollegeAID` ASC),
INDEX `CollegeBID_idx` (`CollegeBID` ASC),
INDEX `CollegeCID_idx` (`CollegeCID` ASC),
CONSTRAINT `CollegeAID`
FOREIGN KEY (`CollegeAID`)
REFERENCES `test`.`CollegeA` (`CollegeAID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeBID`
FOREIGN KEY (`CollegeBID`)
REFERENCES `test`.`CollegeB` (`CollegeBID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeCID`
FOREIGN KEY (`CollegeCID`)
REFERENCES `test`.`CollegeC` (`CollegeCID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
PHP example
if(empty($SchoolA) && empty($SchoolB) && empty($SchoolC)){
$CollegeAId = "";
}
else {
$queryCOLLEGEA = "
INSERT INTO CollegeA (SchoolA, SchoolB, SchoolC)
VALUES('$SchoolA','$SchoolB','$SchoolC')";
$result = mysqli_query($con, $queryCOLLEGEA);
$CollegeAId = mysqli_insert_id($con);
};
if(empty($School1) && empty($School2) && empty($School3)){
$CollegeBId = "";
}
else {
$queryCOLLEGEB = "
INSERT INTO CollegeB (School1, School2, School3)
VALUES('$School1','$School2','$School3')";
$result = mysqli_query($con, $queryCOLLEGEB);
$CollegeBId = mysqli_insert_id($con);
};
if(empty($School11) && empty($School22) && empty($School33)){
$CollegeCId = "";
}
else {
$queryCOLLEGEC = "
INSERT INTO CollegeB (School11, School22, School33)
VALUES('$School11','$School22','$School33')";
$result = mysqli_query($con, $queryCOLLEGEC);
$CollegeCId = mysqli_insert_id($con);
};
$queryMain = "
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('$F_Name', '$L_Name', '$Email', '$CollegeAId', '$CollegeBId', '$CollegeCId')";
$result = mysqli_query($con, $queryMain);
You are using NOT NULL column as foreign key. In this case you cannot leave it empty, you must set here correct key from referenced table. You can change table definition to
CREATE TABLE IF NOT EXISTS `test`.`Teacher` (
`TeacherId` INT(11) NOT NULL AUTO_INCREMENT,
`F_name` VARCHAR(45) NOT NULL,
`L_name` VARCHAR(45) NOT NULL,
`Email` VARCHAR(45) NOT NULL,
`CollegeAID` INT(11),
`CollegeBID` INT(11),
`CollegeCID` INT(11),
PRIMARY KEY (`MainId`),
INDEX `CollegeAID_idx` (`CollegeAID` ASC),
INDEX `CollegeBID_idx` (`CollegeBID` ASC),
INDEX `CollegeCID_idx` (`CollegeCID` ASC),
CONSTRAINT `CollegeAID`
FOREIGN KEY (`CollegeAID`)
REFERENCES `test`.`CollegeA` (`CollegeAID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeBID`
FOREIGN KEY (`CollegeBID`)
REFERENCES `test`.`CollegeB` (`CollegeBID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CollegeCID`
FOREIGN KEY (`CollegeCID`)
REFERENCES `test`.`CollegeC` (`CollegeCID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
In this table you can insert NULL values into CollegeAID, CollegeBID and CollegeCID. So, if teacher works in college, it will have value in appropriate CollegeID. If no - CollegeID will be NULL.
Also you will ned to change your code. Change you code like this
if(empty($SchoolA) && empty($SchoolB) && empty($SchoolC)){
$CollegeAId = null;
}
for all three colleges. You need null, not empty string.
And another change is needed here
$queryMain = "
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('$F_Name', '$L_Name', '$Email', '$CollegeAId', '$CollegeBId', '$CollegeCId')";
Variable $CollegeAId now contains proper NULL value. But this query will be produced into
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('F_Name', 'L_Name', 'Email', '', 'CollegeBId', 'CollegeCId')
See it? Still empty string instead of NULL! You need to change query string. It must looks like
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('F_Name', 'L_Name', 'Email', NULL, 'CollegeBId', 'CollegeCId')
For example, you can do it this way for college A:
$CollegeAId = isset($CollegeAId) ? "'$CollegeAId'" : 'NULL';
$queryMain = "
INSERT INTO Teacher (F_Name, L_Name, Email, CollegeAID, CollegeBID, CollegeCID)
VALUES ('$F_Name', '$L_Name', '$Email', $CollegeAId, '$CollegeBId', '$CollegeCId')";

Cannot add or update a child row: a foreign key constraint fails (Mysql and Foreign key)

When I trying to run the code, this error shows up
Cannot add or update a child row: a foreign key constraint fails
(hotel_info.results, CONSTRAINT results_ibfk_5 FOREIGN KEY
(CustomerID) REFERENCES customer (CustomerID) ON DELETE CASCADE
ON UPDATE CASCADE)
Here is the code
$result = mysql_query("select customer.CustomerID from customer inner join results on customer.CustomerID = results.CustomerID where customer.Username = '".$aid."'");
if (false === $result)
{
echo mysql_error();
}
if (isset($_POST["submitbtn"]))
{
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$checkin = $_POST["CheckIn"];
$checkout = $_POST["CheckOut"];
$unit = $_POST["unit"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
if($checkin>$checkout)
{
?>
<script type="text/javascript">
alert("End Date must greater than Start Date.");
</script>
<?php
}
else
{
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$result')");
if (false === $query)
{
echo mysql_error();
}
echo "Reservation form has been submitted!<br>
<a href=view.php>view all</a>";
}
}
Here is the sql
CREATE TABLE IF NOT EXISTS `results` (
`BookID` int(10) NOT NULL AUTO_INCREMENT,
`LP` varchar(50) DEFAULT NULL,
`budget` varchar(50) DEFAULT NULL,
`CheckIn` varchar(50) DEFAULT NULL,
`CheckOut` varchar(50) DEFAULT NULL,
`unit` int(50) DEFAULT NULL,
`SmokeP` varchar(50) DEFAULT NULL,
`sp_req` varchar(255) DEFAULT NULL,
`CustomerID` int(10) NOT NULL,
PRIMARY KEY (`BookID`),
KEY `Username` (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=48 ;
CREATE TABLE IF NOT EXISTS `customer` (
`CustomerID` int(10) NOT NULL AUTO_INCREMENT,
`Username` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`ContactNo` int(10) NOT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
I've already stuck for two days because of this error, please help.
from the error it is clear that foreign key constraint fails. Please check your customer table which must have CustomerID that you are trying to insert in results table insert query i.e. check value of $id. have you assigned any value for $id
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$id')");
In above query value for $id not set so first assign value to that.

Trying to join certain values in different tables in mysql

i'm very new to mysql and I am trying to create a database that can store users emails and passwords on one table and the values they input on another table, how do I join the tables to make sure that the inputted values are linked to the correct user. This is the code I've been using but it won't allow the value to be stored while the foreign key is run, but if I remove the foreign key I can store the value. Please help.
CREATE TABLE IF NOT EXISTS `data` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(51) NOT NULL,
`password` varchar(15) NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `email_UNIQUE` (`email`)
)
CREATE TABLE IF NOT EXISTS `gluco` (
`G_id` int(11) NOT NULL AUTO_INCREMENT,
`bloods` decimal(4,2) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `data`(`use_id`),
UNIQUE KEY `G_id_UNIQUE` (`G_id`)
)
<?php
include('db.php');
if (!isset($_POST['reading'])) { //checking if user has entered this page directly
include('contactus.php');
} else {
if (isset($_POST['reading'])&&$_POST['reading']==""||!isset($_POST['reading'])) {
$error[] = "fill in your blood/glucose";
}
$reading = mysql_real_escape_string($_POST['reading']);
$sql = "SELECT * FROM gluco WHERE bloods = '$reading'";
if(isset($error)){
if(is_array($error)){
echo "<div class=\"error\"><span>please check the errors and refill the form<span><br/>";
foreach ($error as $ers) {
echo "<span>".$ers."</span><br/>";
}
echo "</div>";
include('contactus.php');
}
}
if(!isset($error)){
$sreading=mysql_real_escape_string($_POST['reading']);
$sip=mysql_real_escape_string($_SERVER['HTTP_HOST']);
$save = mysql_query("INSERT INTO `gluco` ( `bloods` )VALUES ('$sreading')");
if($save){
echo "<div class=\"success\"><span>Your reading has been successfully stored</span><br/></div>";
} else {
echo "<div class=\"warning\"><span>Some Error occured during processing your data</div>";
}
}
}
?>
your code is correct in its logic. But theres an error on the referenced column name:
CREATE TABLE IF NOT EXISTS `data` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(51) NOT NULL,
`password` varchar(15) NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `email_UNIQUE` (`email`)
)
CREATE TABLE IF NOT EXISTS `gluco` (
`G_id` int(11) NOT NULL AUTO_INCREMENT,
`bloods` decimal(4,2) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `data`(`user_id`),
UNIQUE KEY `G_id_UNIQUE` (`G_id`)
)
and on this line:
$save = mysql_query("INSERT INTO `gluco` ( `bloods` )VALUES ('$sreading')");
you are not setting the user_id in your insert statement, so, the foreign key will not work and the insert will not be made. So, you'll need to have the user id stored in a variable (since i don't know the context and the scope in the code, i can't help you setting this variable). So, your code should be like that:
$save = mysql_query("INSERT INTO gluco (bloods, user_id)VALUES ('$sreading', $user_id)");

PDO not inserting more than one row in table

I'm having trouble inserting image data into my database. I have a table called images. When dumped with PHPMyAdmin it looks like this:
CREATE TABLE IF NOT EXISTS `images` (
`id` int(11) NOT NULL,
`orig_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`hash` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
`filename` varchar(12) COLLATE utf8_unicode_ci NOT NULL,
`uploaded` datetime NOT NULL,
`views` int(11) NOT NULL DEFAULT '0',
`album_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`server_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `server_id` (`server_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
This is the code I'm using to insert rows:
// Database connection
$db = new PDO('mysql:host=localhost;dbname=testdb', 'root', '');
// some code...
$st = $db->prepare('INSERT INTO `images` (orig_name, hash, filename, uploaded, server_id)
VALUES (?, ?, ?, ?, (SELECT `id` FROM `servers` WHERE `name` = ?))');
$st->execute(array($origName, $fileHash, $filename, date('c'), $server));
// more code...
// Database cleanup
$st = null;
$db = null;
The script returns no errors, and works flawlessly for the first row inserted. If the script runs again, it fails to insert any more rows in the images table. I see no reason why it'd behave like this, the data going into each field is unique each time (except for the server_id field).
Your id field isn't set to auto_increment.
The first record that you post will be added, with a NULL as id; the second record won't be added because there's already a record with NULL as the primary key, so it'll fail - you don't have any error checking in the code, so it won't be printing out the errors it's getting back.

Insertion Failed:Cannot add or update a child row: a foreign key constraint fails

I have two tables- users and language with a foreign key link of their primary key 'id'.
I have checked that the type is innoDB for the tables. I have delete- restrict and update -cascade.
This insert query, inserts it into the language table: (it can be more than one row which is added as the form has dynamic clickevent button)
if(empty($_SESSION['user_id'])) { // user not logged in; redirect to somewhere else }
$sql_insert = "INSERT into `language`
(`native`,`other`,`other_list`,`other_read`, `other_spokint`
,`other_spokprod`,`other_writ` )
VALUES
('$native','$other','$other_list','$other_read','$other_spokint','$other_spokprod',
'$other_writ') ";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
This is the full error:
Insertion Failed:Cannot add or update a child row: a foreign key constraint fails
(`members`.`language`, CONSTRAINT `language_ibfk_1` FOREIGN KEY (`id`)
REFERENCES `users` (`id`))
Any help would be appreciated!
Table structure for table language:
CREATE TABLE IF NOT EXISTS `language` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`native` varchar(30) NOT NULL,
`other` varchar(30) NOT NULL,
`other_list` varchar(9) NOT NULL,
`other_read` varchar(9) NOT NULL,
`other_spokint` varchar(9) NOT NULL,
`other_spokprod` varchar(9) NOT NULL,
`other_writ` varchar(9) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
RELATIONS FOR TABLE `language`:
`id`
`users` -> `id`
You have to use a structure like this:
create table users (
id int not null auto_increment,
<additional fields>,
primary key (id)
) ENGINE=InnoDB;
create table language(
id int not null auto_increment,
user_id int not null,
<additional fields>,
primary key (id),
foreign key (user_id) references users(id) on delete restrict on update cascade
) ENGINE=InnoDB;

Categories