How to get last insert Id while using custom Execute('Insert Query')

How to get last insert Id while using custom Execute('Insert Query')

by Code Profile -
Number of replies: 2

How to get last insert Id while using custom $DB->Execute('Insert Query')  

Note:

I have separate table name without $CFG->prefix, So I couldn't use the $DB->insert_record query execution, that's why I use Insert query in $DB->execute.

Average of ratings: -
In reply to Code Profile

Re: How to get last insert Id while using custom Execute('Insert Query')

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
I think the simple answer is "you don't" - $DB->execute() doesn't support returning a result and Moodle, in general, does not support inserting into tables without the $CFG->prefix (because then multiple Moodle sites sharing the same DB would end up clashing with one another whilst writing to the same table).

I suppose you could do a query in order to get the highest ID in the table, but, again, there isn't really a clear use-case (that I'm aware of) where it would be desirable to do this in the first place.

Rename the table to include the prefix, if it is a table that should be managed by Moodle. If it is not, then consider using some sort of API to manage it, rather than trying to use the Moodle database functions to access it.
Average of ratings: Useful (1)
In reply to Davo Smith

Re: How to get last insert Id while using custom Execute('Insert Query')

by Mark Sharp -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers
Absolutely agree with this. The alternative is to use built-in PHP functions to do your extra-moodle DB work. e.g. PDO (https://www.php.net/manual/en/book.pdo.php) but this all sounds like extra work for not much reason.