Write more compact php code
Thursday, July 10th, 2008 in PHPI’ve been programming using PHP and MySQL for about 4 years by now. One thing that I’ve always hated was to write code. Don’t get me wrong, I love coding, what I hate is writing in 10 lines what I could do in 5. Besides the fact that is a terrible waste of time and effort, when I was put in the position of revising the code at a later time (to make changes or just for the sake of improving the code) I found myself in trouble trying to understand what the hell I was thinking back then. Another scenario is when someone else is taking what you started ( I know this because I had to take on someone else’s projects ).
Giving this, why not spend a little time thinking first and then start coding? Below are a few things I’ve found out with time.
What I always hated was writing all over again mysql_query(…) … while( $r = mysql_fetch… ), you know what I mean. So I developed a function that retrieves the query results into an array. This has two advantages: first one is that since all queries run using the same function, you can make modifications like adding a mysql_free_result() ( or run an EXPLAIN mysql query if you are using indexes ) after you run the query or you can show of hide mysql errors just as easy, making the modifications only in one place.
Here’s what I mean:
1 2 3 4 5 6 7 8 9 10 11 | function retrieve_data( $sql , $mode = 'mysql_fetch_assoc' ) { $results = array(); $query = mysql_query( $sql ) or die( mysql_error() ); while( $r = $mode( $query ) ) { $results[] = $r; } mysql_free_results( $query ); return $results; } |
See what I mean? And to use this, you only have to write the $sql parameter
1 | $results_from_db = retrieve_data("SELECT * FROM my_table"); |
Just one line in your code and you have all the data stored in $results_from_db. To display the data you’ll probably use for() or foreach().
1 2 3 4 5 6 7 8 9 10 11 12 | // example using for $total_rows = count( $results_from_db ); for( $i = 0 ; $i < $total_rows ; $i++ ) { echo $results_from_db[$i]['a_column_name_from_my_table']; } // and using foreach() foreach( $results_from_db as $line ) { echo $line['a_column_name_from_my_table']; } |
The advantage is that when you finish the project, in order not to show the mysql errors (if any), you simply change this:
1 | $query = mysql_query( $sql ) or die( mysql_error() ); |
into this
1 | $query = mysql_query( $sql ) or die( 'Sorry mate, we encountered a technical difficulty.' ); |
Remember I said something about 2 advantages? Well, the second would be this one. I’ve encountered the following problem in some cases: I had a query and I needed to show the results in more than just one place. Basically, I had to run mysql_query()…while(…) two times to show the same thing because you can’t use a while on the same query two times. Of course, you can generate an array with the results first and then use it in both places but… this is what our function does. Come to think of it, this is not a very good second reason. I’ll have to think better.
Another code compacting little thing is preg_replace(). Let’s say that you have a website with articles and you need to generate URL’s having the article title on the link ( people say it’s good for SEO :) ). So, what do you do? A preg_replace of course. We only want to keep alphanumeric characters, no spaces, no dots, no commas or any other thing. Ah, and we want to replace spaces with ‘-’. Here we go:
1 2 3 | $article_title = 'Some corny title - do it yourself in 5 minutes'; $formatted = preg_replace("([^\w-])",'-',$article_title); echo $formatted; |
That’s it! One line of code.
Now, let’ say you have article id’s coming on the like ( http://somesite.com/article.php?article=1 ). How can we make sure that some wise guy won’t try some sql injection crap on us? We simply set the variable as an integer.
1 2 | $sql = "SELECT * FROM article_table WHERE article_id = '".((int)$_GET['article'])."'"; // run sql and see if the article exists |
No matter what you’ll write on the link ( instead of the article id ), the sql will be safe from sql injection because the variable value will be transformed into an integer.
Want to make a simple check on a variable? Let’s say that we have a variable holding a boolean value and we want to display a different thing according to that value. Here goes:
$value = true; echo $value ? 'Value set to true' : 'Value set to false';
Well, that’s it for now. One thing to remember though is that you must not write code that it’s not as readable as you’ll like it to be if you follow someone else’s steps. I mean variables like $t that holds some global configuration value and it’s declared in top.php and used in some page somewhere. Or doing a “global $variable” in a function in order to make reference to a variable declared outside the function and even worst, making changes to it and than use it in another function and … I’m getting dizzy just thinking at such thing. But that is another subject.






4 comments
Hello,
have you considered using a framework? Like Zend Framework? that is generally helping to prevent writing too much code by offering convenience methods for database retrieval and many other goodies.
Hi,
I was thinking one time of using a framework and tested a little on CakePHP. Besides the fact that the example they gave on the manual was out of date ( didn’t work on the current version ), I also tested and found out that script execution was a little bit slow. I tested using the profiler in Zend Development Enviroment.
I’ll take a look though at Zend Framework. Didn’t used it but I’ll give it a shot.
Hey thanks, especially with the database function. I recently began teaching myself php and mysql since my father wanted a site for his company, and hopefully this very function will help me with a problem I have right now, thanks! (sorry, no digg, I am currently registered on way to many sites and I don’t want to register on another one, but you still have my thank you :))
The user could still use a negative integer on your example.
I agree with some of your methods however I still like to have readable php / mysql. After 5/6 years of PHP, I have a custom written framework of useful functions that I use over and over in personal projects. Especially regular expressions. Some people create thousands of functions for a single regular expression that could be simplified to one function with a switch.
Leave a comment