我遇到了数据库设计的一个重大缺陷。以下是我的四个表:
会话表:
SessionId SessionName
3 EROEW
问题表:
QuestionId(PK) QuestionNo QuestionContent SessionId (FK)
11 1 Question1 3
12 2 Question2 3
13 3 Question3 3
Image_Question:
ImageQuestionId (PK) ImageId (FK) SessionId (Fk) QuestionNo (FK)
1 1 3 1
2 2 3 2
图片:
ImageId (PK) SessionId (Fk) QuestionNo (FK)
1 3 1
2 3 2
现在您可以在Image_Question
表中看到,QuestionNo
指的是QuestionNo
,它是非唯一的,换句话说是非唯一字段。现在我认为这是不好的做法。
现在我知道你会说为什么不使用QuestionId
。好吧问题是我无法使用QuestionId
,因为在提交问题之前将图片上传到每个问题,我们可以在用户提交后自己QuestionId
提出问题的唯一方法问题。
所以我尝试做的是通过从页面获取QuestionNo
以及SessionId
来确定上传图片属于哪个问题。
现在我听说这是一种不好的方式,我想将QuestionNo (FK)
中的Image_Question
更改为QuestionId (FK)
。但是,在提交问题后,我无法上传文件并插入上传的详细信息,以获取QuestionId
给我无法完成的内容。
所以我的问题是,我们可以通过某种方式将每个上传的图像存储到临时表中,获取每个图像所属的问题编号和sessionid,然后从那里找到QuestionId
并将QuestionId
值存储在Image_Question
表中?
以下是我当前的PHP代码,它会在上传图片后插入值:
如果有人可以更新以下代码,那就太棒了,但任何答案都会有所帮助:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES (?)";
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name']; //GET THE IMAGE UPLOADED
$insert->execute();
$insert->close();
$lastImageID = $mysqli->insert_id;
$_SESSION['lastImageID'] = $lastImageID;
$_SESSION['ImageFile'] = $_FILES["fileImage"]["name"];
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : ''); GET THE NAME OF THE SESSION
$sessionquery = "SELECT SessionId FROM Session WHERE (SessionName = ?)"; //FIND SESSIONID by finding it's SESSIONNAME
// Bind parameter for statement
$sessionstmt->bind_param("s", $sessid);
// Execute the statement
$sessionstmt->execute();
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$sessionstmt->bind_result($sessionid);
// This populates $sessionid
$sessionstmt->fetch();
$sessionstmt->close();
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionNo) //INSERT DETAILS INTO CURRENT IMAGE_QUESTION TABLE
VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err imagequestion";
}
$qnum = (int)$_POST['numimage']; //QUESTION NUMBER IMAGE IS UPLOADED IN
$insertimagequestion->bind_param("iii",$lastImageID, $sessionid, $qnum);
$insertimagequestion->execute();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
答案 0 :(得分:1)
您最大的问题是您的架构未正常化。这样做可以帮助你 以下是我建议您构建数据库的方法:
<强>会话强>
SessionId SessionName
3 EROEW
<强>问题:强>
QuestionId(PK) QuestionContent SessionId (FK)
11 Question1 3
12 Question2 3
13 Question3 3
图片:强>
ImageId (PK)
1
2
<强> Image_Question:强>
ImageId (FK) QuestionId (FK) -- (Composite primary key)
1 11
2 12
表的插入顺序应为:
Session -> Question -
\
-- Image_Question
/
Image -
您将避免潜在的更新问题,否则数据会发生冲突。