Possible Duplicate:
Access Auto-Increment Value During INSERT INTO Statement
I would like to generate the slug for my URLs upon creating the pages to store in the database. The slug should be title-id (e.g titlename-234). I already have the function to strip the title but how can i get the id before inserting the record?
Many thanks in advance
You should create a trigger, something like that:
I’m not sure you’ll be able to access the ID column before its written on the database (unless, of course, you generate your IDs yourself, not using the autoincrement).
If you’re using your DB’s autoincrement (and you should be), try creating a trigger AFTER INSERT, and updating your row in your trigger. That way, even though you’re updating it AFTER your insert, it’ll still run before you can run any other queries (like a SELECT).
HERE is the documentation on triggers.
I was wrong. Apparently, you can’t update a table you’re inserting into (using an AFTER INSERT triger), it’ll throw an exception. So, two possible ways to do it using SQL alone:
The ugly way:
It overrides your database’s AUTOINCREMENT. Really, don’t do that.
Or, you can create a procedure:
And, instead of calling (as you were calling):
just call
Again, I’ll strongly advice against using mysql_query. It’s outdated, discontinued and unsafe. You should check out mysqli or PDO.