开发者

How to get the ID of a mysql row before INSERT

开发者 https://www.devze.com 2023-04-05 11:57 出处:网络
I can get the ID just after INSERT by mysql_insert_id(); but I want to save an image in the fo开发者_运维知识库rm of ID-image_name.jpg and save it in a column named Image_Name. How can I save the imag

I can get the ID just after INSERT by mysql_insert_id(); but I want to save an image in the fo开发者_运维知识库rm 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?


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'");


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).


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消