The following warnings occurred:
Warning [2] Undefined variable $unreadreports - Line: 26 - File: global.php(961) : eval()'d code PHP 8.1.2-1ubuntu2.14 (Linux)
File Line Function
/global.php(961) : eval()'d code 26 errorHandler->error
/global.php 961 eval
/printthread.php 16 require_once



UserSpice
Get the latest inserted ID - Printable Version

+- UserSpice (https://userspice.com/forums)
+-- Forum: Miscellaneous (https://userspice.com/forums/forumdisplay.php?fid=28)
+--- Forum: Documentation (https://userspice.com/forums/forumdisplay.php?fid=30)
+--- Thread: Get the latest inserted ID (/showthread.php?tid=303)



Get the latest inserted ID - GePraxa - 10-06-2016

This is not working, as I have to?

<?php
if(isset($_POST['submit'])) {

$db = DB::getInstance();

$fields=array(
'var1' => $var1,
'var2' => $var2
);
if($db->insert('table',$fields)){
$yes[] = 'text';
}else{
$no[] = 'text';
}

$last_id = $db->lastId();
}
?>


Get the latest inserted ID - mudmin - 10-06-2016

I think it is an issue of scope. You are trying to pull back the lastId outside of the if statement. It should be...

if($db->insert(‘table’,$fields)){
$last_id = $db->lastId();
$yes[] = ‘text’;
}else{
$no[] = ‘text’;
}
}
?>


Get the latest inserted ID - plb - 10-06-2016

I agree that your code, Mudmin, is better because it doesn't try to get the $last_id if the insert was unsuccessful. But I've never heard of scope issues like this in PHP related to an if statement...

@GePraxa, when you say it wasn't working, what was not working? Is it possible your insert was failing and that was causing the problem?


Get the latest inserted ID - mudmin - 10-06-2016

Maybe I'm wrong there, but I've seem to remember that if you don't pull the lastId back almost immediately I've had a hard time getting it back.