I for my sins code in PHP,Perl,ColdFusion using database MySQL and also write JavaScript, XML and battle with CSS and Ajax etc. Often I’m working on these projects in parallel which gets kind of stressful. Anyway I let my standards slip recently and made the following mistakes and suffered for it.
- Not immediately taking my own backup of the files I was working so I could rollback at any time and as importantly prove whether my changes had or had not caused a regression or bug
- Leaving test files lying about, so I later got confused as to which was the actual version
- To my credit have been using git for version control
Coding Tips
git, rollback
preg_match_all(‘#<b>.+?</b>#i’, $html, $matches);
// ? means non-greedy and is absolutely critical
$match[1], $match[2] contain the results
Non greedy stops the match gobbling everything between the first bold tag and the very last. I’ve never quite understood why greedy is the default behavior of RegExp (Regular Expressions) but I guess there’s a good reason for it.
PHP also has the very useful strip_tags function.
Coding Tips, PHP
regex
This for loop is OK
foreach($cargo_data as $cid=>$cargo_record)
{
$cargo_id=$cargo_data[$cid]['cargo_id'];
$section=$cargo_data[$cid]['section'];
…
}
But then later you add a condition cargo_id>6
foreach($cargo_data as $cid=>$cargo_record)
{
if ($cid>6) {$cargo_id=$cargo_data[$cid]['cargo_id'];}
$section=$cargo_data[$cid]['section'];
…
}
Now the bug is that if $cid is less than 6 $cargo_id is not set and will likely inherit the value it was set to in the last loop this type of error may not be immediately noticeable but can cause chaos. In this simple example it is easy to see that their should be an else clause, however the real solution is to systematically initialize all the variables at the beginning of the loop.
Coding Tips
I had been using my own ad-hoc system for years but recently started using CVS to maintain a history of my file and document changes. I was quite happy with CVS but everyone told me I should be using Git instead. Git seems to be simpler and more intuitive. I can set up git for a folder or project very quickly. You just need the following 5 commands to get going
git init (set up git for the current directory)
git add *.php (add all your php files or whatever)
git commit -m “first version” (also need to commit all your existing php files)
vi index.php (make a few changes)
git commit -a -m “Added new date feature” (do this periodically to maintain version control)
gitk is a simple TK Gui which allows you to review you versions etc. I am delighted to have version control, all I have to do is remember to do a > git commit -a -m “Added new date feature” every now and again (eg daily)
Coding Tips
Coding Tips, cvs, gitk, version control