Generating Unique ID’s in PHP

There may be situations where you need to generate a unique string. I have seen many people use themd5() function for this, even though it’s not exactly meant for this purpose: // generate unique string echo md5(time() . mt_rand(1,1000000)); There is actually a PHP function named uniqid() that is meant to be used for this. // generate unique… Continue reading Generating Unique ID’s in PHP

Update Multiple Rows With Different Values and a Single SQL Query

Sometimes you may need to update multiple rows of data in a table. This is no problem a lot of the time, as the fields to update may all need to be changed to the same value, in which case you might run a query like the following. UPDATE mytable  SET myfield = ‘value’  WHERE other_field = ‘other_value’; But what about if… Continue reading Update Multiple Rows With Different Values and a Single SQL Query

Avoid doing SQL queries within a loop

A common mistake is placing a SQL query inside of a loop. This results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once. foreach ($userList as $user) { $query =… Continue reading Avoid doing SQL queries within a loop

Don’t copy variables for no reason

Sometimes PHP novices attempt to make their code “cleaner” by copying predefined variables to variables with shorter names before working with them. What this actually results in is doubled memory consumption (when the variable is altered), and therefore, slow scripts. In the following example, if a user had inserted 512KB worth of characters into a… Continue reading Don’t copy variables for no reason