Control duplicate entries in Hook Post
You're using mysql_query, which is deprecated in both PHP and modern versions of Civi.  The code isn't running forever, it's failed with an error - you should be able to find that error, most likely in your CiviCRM log.  

While you could use mysqli_query, the better choice is to use a wrapper, which should give at least partial future-proofing.  Here's my (untested!) attempt at a rewrite:

Use:



$check = CRM_Core_DAO::executeQuery("SELECT * FROM table WHERE code = '$invoicenum'");

if ($check-&gt;fetch()) {
  // WARNING
else
  // OK
}


Note also that if you're using the post hook, the data has already been written to the database.  I would put this in a validation hook or an API Wrapper hook if you're trying to prevent the data being written.