When You're first checking what's max. order ID in database and then You're creating new reference number based on that, You will always have problem when 2 clients will use that function in same time.
To solve this problem, You must first create order, return ID of that new order and then create new reference number based on that returned ID.
That's why, I'm checking database for same reference number in my example above. It's not perfect, but almost no chance to generate RANDOM reference by 2 clients in same time.