You just said what you'd have to do, make a number and run query to see if it's free.
Unfortunately it's not quite that simple.
PHP/webserver is multi-user, several people can enter new records into the database, so it is possible that two people come up with the same number, andboth run a query to see if it exists, both will see it is free, and both will enter a record. Boom: duplicate number. (that will happen)
Does the number have to be random?
if you only need a unique number, just use a sequence, or as MySQL calls it: auto_increment.
That brute force "create a number and see if it works" can really load your database as the amount of free numbers get's smaller.