我使用下面的代码上传文件并使用mysqli将数据插入“Image”表:
<?php
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
//UPLOAD IMAGE FILE
move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
//INSERT INTO IMAGE DATABASE TABLE
$imagesql = "INSERT INTO Image (ImageFile) VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
//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'];
$insert->execute();
$insertimagequestion->execute();
//IF ANY ERROR WHILE INSERTING DATA INTO EITHER OF THE TABLES
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";
}
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$insertimagequestion->bind_param("isi",$lastID, $sessid, $_POST['numQuestion'][$i]);
$insertimagequestion->execute();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
}
?>
例如,如果我将2个图像“cat.png”和“dog.png”插入“图像”数据库表中,它将像这样插入:
ImageId ImageFile
220 cat.png
221 dog.png
(ImageId is an auto increment)
无论如何,我想要做的是,当上传文件时,不仅将数据插入到上面的表中,而且我还希望能够检索上面插入的ImageId并将其放在“Image_Question”中“下面的表格就是这样:
ImageId SessionId QuestionId
220 AAA 1
221 AAB 4
但它没有在Image_Question表中插入任何内容。如何上传图像,它不仅可以将数据插入“图像”表,还可以将数据插入“Image_Question”表中?
答案 0 :(得分:1)
原谅我,如果我离开了,但不是php顺序执行,换句话说,
不应该这样:$insertimagequestion->execute();
追求这个:if (!$insertimagequestion = $mysqli->prepare($imagequestionsql))
?
也许$insertimagequestion->execute();
的第一次出现可能会消除插入ID。我会把东西打印出去确保你获得了insert_id。