0

I have a INSERT function where it inserts the image filename in the 'ImageFile' field in the "Image" table, each row has it's own ImageId thanks to auto number. An example of this is below:

ImageId    ImageFile

23         orange.jpg
24         flowers.png
25         castle.png
26         orange.jpg

What I want to do is also insert the ImageId into another table with the QuestionId and SessionId so that this table (Image_Question) can use the ImageId to link the Image table with the Image Question table. But how do I code it so that when I insert image details in the table above, then it will retrieve it's ImageId and also store it in the ImageId in the Image_Question table. Example below:

ImageId   SessionId  QuestionId

23        AAA        1
24        AAA        2
25        AAA        3
26        AAA        4

I have coded the INSERT values for SessionId and QuestionId but just need help retrieving and inserting the ImageId. Below is the current code:

<?php

session_start();


//connect to db

$i = 0;

$insertimage = array();

for($i = 0;  $i < $c; $i++ ){


    $insertimage[] = "'". mysql_real_escape_string($_SESSION['id'] ) . 
                    ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '') ."' ,'". 
                    mysql_real_escape_string( $_POST['numQuestion'][$i] ) ."'";

}


 $imagesql = "INSERT INTO Question (ImageId, SessionId, QuestionId) 
    VALUES (" . implode('), (', $insertimage) . ")";

echo($imagesql);

mysql_close();


?>
user1394925
  • 754
  • 9
  • 28
  • 51
  • Please stop writing new code with the ancient MySQL extension: it is no longer maintained and the community has begun the [deprecation process](http://news.php.net/php.internals/53799); you can use instead either the improved [MySQLi](http://php.net/mysqli) extension or the [PDO](http://php.net/pdo) abstraction layer. – eggyal Jun 05 '12 at 22:43
  • @eggyal Looking at your documentation you provided me, do I just change majority of my code from "mysql_..." to "mysqli_..."? – user1394925 Jun 05 '12 at 22:52
  • To use MySQLi, yes. There are even [tools](http://forge.mysql.com/wiki/Converting_to_MySQLi) that will do the conversion for you. However, as that wiki notes, you should also take advantage of the extra benefits that [prepared statements](http://stackoverflow.com/a/60496/623041) can bring. – eggyal Jun 05 '12 at 22:55

2 Answers2

1

mysqli_insert_id() after query execute would do the trick

user2056342
  • 195
  • 3
  • 15
0

You can get the most recently generated auto_increment id using MySQL's last_insert_id() function. PHP exposes this through mysql_insert_id(). last_insert_id works on a per-connection basis so there is no need to worry about concurrent inserts crossing ids.

Asaph
  • 159,146
  • 25
  • 197
  • 199