我在下面有一些 php 代码将数据添加到 2 个表中,一个称为“Image Table”,另一个称为“Image_Question”表。我面临的问题是当它插入“图像”表时,它不会将任何数据插入“图像问题”表中。
现在我知道 PHP 代码很好,因为它曾经能够毫无问题地将数据插入到两个表中。
只有在我向表中添加索引和外键之后,这个问题才开始发生。
下面是将数据插入两个表的 PHP 代码:
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();
这是SHOW CREATE TABLE
Image Table、Image_Question Table 和 Question Table 的输出,因为 Image_Question 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 表:
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
问题表:
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