Search code examples
phpmysqlfunctionlast-insert-id

getting value from 'last_insert_id()', the php function


I have a problem with getting a value from 'last_insert_id()'.. I want to insert a same id number to id of table 'memo'. However, the problem is after foreach, last_insert_id() gets a new value, so, I tried to make a variable and get a value from 'last_insert_id()', but it didn't work..

$diary_id = 'last_insert_id()';

foreach ($_POST['memo'] as $memo) {
     echo "You selected: $diary_id <br>";
     echo "You selected: $memo <br>";

 $query_test = "insert into memo(memo_no,id,memo)
    values(NULL,$diary_id,'$memo')";
 mysql_query($query_test, $connect);

}


Solution

  • Use mysql_insert_id function in php to get the last previous AUTO INCREMENTED generated id. Use the code below

    $diary_id = mysql_insert_id();
    
    foreach ($_POST['memo'] as $memo) {
         echo "You selected: $diary_id <br>";
         echo "You selected: $memo <br>";
    
     $query_test = "insert into memo(memo_no,id,memo)
        values(NULL,$diary_id,'$memo')";
     mysql_query($query_test, $connect);
    
    }
    

    Hope this helps you