tags:

views:

67

answers:

3

I'll try to make myself clear with an example:

Imagine an admin page to add a product to a database (product list). When I open the ADD ITEM page, the item is not yet created (not until I click the submit button), but let's say I want to add categories this product will appear in (with AJAX for example). When I run the AJAX script, i need to tell it which ID (my product) to put these categories in...

How should I do this.?

Is inserting a blank item in the database (to get mysql_insert_id) when the page opens a good way to do this.? Is it prone to conflicts or errors..?

I'm afraid this technique will populate the DB with lots of empty product because of admins reloading the page, leaving the page before submitting, etc...

How do you guys do it.?

+1  A: 

I use a GUID as my IDs on stuff like this which you can generate on pretty much any system. (But use the libraries!)

drachenstern
I use GUIDs as well providing you do not need to display them to the user
Rob Goodwin
@Rob Goodwin I never really present them with a unique ID unless it's necessary. I will, however, provide them a pseudoID for things like speed lookups. But that's just an indexable field.
drachenstern
+1  A: 

When you add the categories via JS, don't post back to the php script, but add form elements to the page's form. You can add hidden input elements with the name category_id[]. That way, nothing is changed in the DB until you actually submit the item form. Then, in the item controller in php, all you need to do is after adding the item, add the categories...

ircmaxell
A: 

I would agree with ircmaxell. You shouldn't be posting to the database until all your form elements are filled. You can use ajax or whatever to alter which form elements are displayed when, but its a good idea to make all your database inserts at once.

Logic Artist
I think this is nonsense. Make database inserts when it makes good business sense to do so, otherwise you'll lose something along the way. However, I don't object to grouping the calls as effectively as possible. The database engine is a helluva lot more powerful than we tend to think it is (sure it's possible to overload it, but write things to be as efficient as they should be and tune the system LATER).
drachenstern