I am using the code below that uploads a file and inserts data into the “Image” table using mysqli:
<?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();
}
?>
So for example if I insert 2 images “cat.png” and “dog.png” into “Image” Database table, it will insert it like this:
ImageId ImageFile
220 cat.png
221 dog.png
(ImageId is an auto increment)
Anyway what I want to do is that when a file is uploaded, not only is the data inserted into the table above, but I want to also be able to retrieve the ImageId that was inserted above and place it in the “Image_Question” table below so it would be like this:
ImageId SessionId QuestionId
220 AAA 1
221 AAB 4
But it is not inserting anything in the Image_Question table. How when I upload an image, it not only inserts data into the “Image” table but be able to insert the data into the “Image_Question” table as well?
Forgive me if I’m way off, but doesn’t the php execute sequentially, in other words,
Shouldn’t this:
$insertimagequestion->execute();go after this:
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql))?
Perhaps the first occurrence of
$insertimagequestion->execute();is wiping out the insert id. I’d put in something to print & make sure you’re getting the insert_id.