quello da te posto è un tipico problema che si risolve con le transazioni. Se il tuo database MySQL supporta le tabelle di tipo InnoDB il gioco è fatto.