25th
Dec
2005
Posted in
Blog :: PHP Do-Nots
I realise I haven't thrown my PHP readers a bone for a while. Lately, unfortunately, all my experience has been with how not to do things. Some of this has been my own fault, but a really healthy percentage has come because I am maintaining one horrible project and rewriting another even more horrid. So, a few pointers for you l3et coders out there: Don't do any of this stuff.
- Some of this is just amateur design. I HATE picking through html 3.2 (lots of tables, no indentation) interspersed with php code (the last hundred lines of nested tds is in an if that doesn't get executed). Would it kill you to have an include file with the mysql connection string instead of retyping it in every file? Oh, wait, I see that you are connecting to the database every time you do a query (yes that's 5-20 mysql_connect() function calls hard coded in each page of spaghetti.) Never mind; somebody is copying and pasting from The Complete Moron's Guide to Learning PHP in 24 Hours Unleashed! (where every code sample has a database connect statement...)
- Some is garden variety ignorance. You are aware, I hope, that relational database products have the ability to do joins between tables. It is not necessary, in fact, to loop over one result set and manually construct a new query to retrieve data from another table based on a foreign key. More subtly, you probably shouldn't call "select *" on a table of 200+ columns when all you want to retrieve is the primary key ("select * from foo" is less performant than "select id from foo" as a query (think about why), plus you're going to get back large array for each result when you only want a single integer...
- Perhaps slightly more complex: a very common scenario in web driven database apps is printing out a table of form elements where each row corresponds to a row in the db and saving all the rows upon submittal of the form. The form handling logic should not be implemented by attaching an id to each element via string mangling (ie fname_1, lname_1, fname_2,lname_2, etc) and then on submittal looping through every single post element, passing it to a gigantic if/else statement, constructed of preg_match calls (if(preg_match("fname_[\d]+", $val))) and then composing a separate update sql statement for every single form element ( "update foo set fname=$value where id=$id" ). Yes the performance of this update sucks to the nth degree. Ix nay the regular expressions and try to run one update per row instead of one update per field. On a 20 field, 30-50 row table this was generating 1000 update queries instead of 50...
Posted on Dec 25th 2005, 10:45 PM