Month: February 2012

February 7, 2012

The Toolbelt: Some of my most-used code snippets for PHP, MySQL, HTML and CSS.

I’ve meant to work on this for quite a while. These are some of my most used code snippets to shorten a process, handy workarounds, pieces of code I need all the time or other such things.

HTML: The Meta Redirect

Use case: You need to redirect someone to another page, and don’t want to bother notifying them.

Code: [code][/code]

Advantages: Silent, works cross-platform, timer can be set (in whole seconds) by adjusting the 0 in content, will work in the body even though it’s a meta tag.
Disadvantages: Breaks back buttons.

PHP/MySQL: Quickly process and sanitize form data.

Use case: You’ve just accepted a form and want to easily work with the data, and escape the data to prevent SQL injection attacks.

Code: [code]foreach($_POST as $key=$value) { $$key=addslashes($value); }[/code]

Advantages: Saves a lot of repetitive entering of $_POST[‘element’]. Instead you just use $element. Also escapes the data early on so we don’t forget further along in the code.
Disadvantages: You create a lot of variables instead of one array. Your array isn’t actually destroyed, just copied. The idea is that the backend is working primarily with this POST data so making a lot of variables isn’t an unwanted thing.

PHP/MySQL: Save an if statement on every mysql_error() check.

Use case: You need to use mysql_error() function to handle errors in your SQL statement.

Old code: [code]$result = mysql_query($query);
if(!$result) { die(mysql_error()); }[/code]

New code: [code]$result = mysql_query($query) or die(mysql_error());[/code]

Advantages: Reduces risk of typos breaking your page, cleaner.
Disadvantages: No known disadvantages.

PHP/MySQL: One standardized method of DB querying.

Use case: You want to get in the habit of one naming scheme for your MySQL queries, and don’t want to go the OOP route.

Code: [code]function doQuery($query) {
$result = mysql_query($query) or die(mysql_error());
return $result; }

…… (More) “The Toolbelt: Some of my most-used code snippets for PHP, MySQL, HTML and CSS.”