View Single Post
  #5 (permalink)  
Old Aug 10th, 2007, 16:41
ioncube ioncube is offline
Junior Member
Join Date: Aug 2007
Location: London
Posts: 45
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Check my tutorial please

Quote:
Originally Posted by alexgeek View Post
i hadn't got round to checking and testing the code yet

Not bad then all things considered

A download link to a zip and tar.gz archive with the files in would probably be appreciated by someone wanting to test it as it would save them cutting and pasting. As well as adjusting colours, a smaller font might make it easier to read too.

With the database schema, you have NOT NULL for the first column, but not on the others. It's usual to specify all columns as NOT NULL as it saves one bit of storage per field and is marginally more efficient. Having a null flag is sometimes useful so that you can distinguish between the default value, e.g. 0 or empty string, and really having no value, but almost always it's not required.

There's also no primary key but this is required if using auto_increment. Adding PRIMARY KEY(id) to your create table would fix that.

Adding UNIQUE will create a unique index, but with such a long key this is inefficient and unnecessary as you're checking for this in the code. Similarly for adding UNIQUE on email. You can create indices for string fields, but this is usually to improve efficiency of searching and not to enforce uniqueness, and the length of the key would be limited to a more reasonable size.

e.g. CREATE INDEX by_username ON users (username(4));

to create the index based on the first 4 characters of the field username.

Assuming that the unique index is gone, there is a potential race condition due to lack of table locking. What could happen is that one request looks up username XXX, determines that it doesn't exist, and before the code gets to do the insert, another request has done the same for the same username and has performed the insert. There are now two entries for the same username. Of course this is highly improbable and we might go so far as to say that it would never happen, but problems with race conditions stem from people being lazy and not getting into the habbit of looking for such issues so that when the time comes for them to code a solution where a race condition is actually quite possible, they are unaware and the design flaw creeps in.

The solution is to get a write lock on the username table, do the lookup, insert if the username is unique, and then unlock tables. Acquiring the write lock will only succeed for one request and will block others (they wait until the lock is released), so you prevent two requests both determining that the same username doesn't exist and trying to insert.

Last edited by ioncube; Aug 10th, 2007 at 16:48.
Reply With Quote