I have a mysqli code below where it uploads a file and insert data into the “Image” Table:
<?php
session_start();
$username="xxx";
$password="xxx";
$database="mobile_app";
$mysqli = new mysqli("localhost", $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$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();
}
}
?>
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 my question 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 cat.png 1
221 dog.png 4
MY question is that how do I retrieve the ImageId from the Image Table and insert it into the Image_Question Table? Below is my code which will insert data into the Image_Question table using mysql, just need to be able to retrieve the ImageId from the Image Table:
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId)
VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
}
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$insertimagequestion->bind_param("sss", $sessid, $_POST['numQuestion'][$i]);
$insertimagequestion->execute();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
After the first insert, you can use mysqli_insert_id to get the id, and the use that when you do the second insert into Image_Question.