Save uploaded image with unique name, create thumbnail and write db only if all goes well
<p>I'm coding a php script to get an uploaded picture, move it in a folder (let's say "/img") renaming it with a unique name, create a thumbnail with the same name in a subfolder ("/img/small"), and insert a record for the picture in my database where the picture's name is the primary key.</p>

<p>Basically I'm obtaining the unique name from the database itself, after an INSERT INTO, with mysql_insert_id. This means that I'm moving the picture and creating the thumbnails <em>after</em> the database insertion, so if something goes wrong (e.g.: invalid image format, not enough space, etc.) I should perform a "DELETE" from the database, pseudocode:</p>

<blockquote>
  <blockquote>
    <p>perform "INSERT INTO ..."<br>
    name = inserted_id<br>
    if (!move_file(temp, "/img/" + name)) perform "DELETE WHERE id = name"<br>
    if (!create_thumbnail(temp, "/img/small" + name)) perform "DELETE WHERE id = name"</p>
  </blockquote>
</blockquote>

<p>I'd like to know if some of you faced the same problem and came out with a more rational and elegant solution.</p>
