Googlebot
Googlebot

Reputation: 15683

How to get the ID of a mysql row before INSERT

I can get the ID just after INSERT by mysql_insert_id(); but I want to save an image in the form of ID-image_name.jpg and save it in a column named Image_Name. How can I save the image with forthcoming ID? Or it is better to save the image file after INSERT process?

Upvotes: 4

Views: 8788

Answers (4)

Richard
Richard

Reputation: 30628

As others have said, you cannot reliably get the ID before the INSERT.

If it is a requirement that the image filename match the row ID, I'd stick with mu's suggestion (INSERT in a transaction, save the file, UPDATE the row, COMMIT the transaction).

An alternative (if you don't have the requirement of id matching filename) would be to name the file using uniqid(). This would allow you to save the file and INSERT the row with a single query and without holding a transaction open.

Upvotes: 0

Mostafa Mahdieh
Mostafa Mahdieh

Reputation: 986

You can save the image with a temporary unique name such as a 20-letter random string, and rename it when the insertion is finished.

Upvotes: 0

mu is too short
mu is too short

Reputation: 434865

Yes, it is better to save the image after the INSERT. You'll want to undo the INSERT (either using DELETE or rolling back the transaction) if saving the file fails of course. If you use a standard naming scheme then you won't have to touch the database again to set the filename in the table (because there wouldn't need to be a filename in the table).

Upvotes: 5

Pekka
Pekka

Reputation: 449753

Saving it after the INSERT process is the most straightforward way.

mysql_query("INSERT INTO....."); // etc. etc.
$id = mysql_insert_id();
mysql_query("UPDATE table SET image = '$image_name' WHERE id = '$id'");

Upvotes: 6

Related Questions