Generating Random Strings in PHP

Generating random strings is a frequently used programming technique. Random string are practically everywhere. For example, you may need to generate a random password, e-mail activation code, various keys and so on. Strangely enough, most of the programming languages and development platforms don't have such functionality built-in. Today we'll look how to develop this in PHP. To have a clear target, our goal is to create a function that generates random strings or arbitrary lengths from a predefined character set. We will present you with two different techniques. The first one is simpler to implement and maintain but can be slightly, just slightly slower then the second version.
However, when it comes to a compromise between simplicity, clarity and performance we choose simplicity and clarity. (This does not mean that we ignore performance, however you should not look at performance as is. Rather, you shall view the application as a whole. What do you prefer, a lightning fast payroll application cutting one 0 from your salary from time to time or a slower application printing your salary correctly all the time. This is a topic who may well make a whole book and we promise to publish several posts on code and application quality).

function randomString($length)
{
   // we have a habit to name return value variables as result
   $result = "";

   // predefined character set
   $charset = "abcdefghijklmnopqrstuvwxyz0123456789";

   $i = 0;

   while ($i < $length)
   {
      // pick a random character from the charset
      $char = substr($charset, mt_rand(0, strlen($charset)-1), 1);

      // we generate random string with no repeated characters
      // that's why we reject a character if it's already in the $result
      if (!strstr($result, $char))
      {
         $result .= $char;
         $i++;
      }
    }
   return $result;
}


The second version is almost the same but instead of picking up the characters from a predefined charset string, we get it from a function which takes a random number and returns a character.


function getRandomChar($num)
{
    switch($num)
    {
       case "1":
          return "a";
          break;
       case "2":
          return "b";
          break;
       case "3":
          return "c";
          break;
       case "4":
          return "d";
          break;
       ... // so on for all chars
    }
}



function randomString($length)
{
   $result="";
   if($length>0)
   {
      for($i=1; $i<=$length; $i++)

      {
         $num = mt_rand(1,36);
         $result .= getRandomChar($num);
      } 
   }
   return $result;
}

The second version is slightly faster however it is more complex and less flexible. For example, if you wanted to change the charset (e.g. include new chars like .,# and so on), in the first version you would just add them to the $charset variable. However, with the second version you would have to update the switch construct in the getRandomChar function. So, our preference goes to version one.

Fun With Nullables: Nullable object must have a value

Nullable types is a great addition to the .NET framework. Having nullable types allows us write cleaner code. However, nullable types can be a source of problems, especially if you are still not well familiar with them. While there is no rocket science involved with nullable types, for beginner developers nullable types seem complex.

Under the hood, nullable types are instances of the System.Nullable<T> struct. In other words, nullable types are in essence generic types and the short and nice question mark that you append to types is just so called syntactical sugar.

So, let's bring one instance of using nullable types where things can go wrong. Look at the code snippet below.

DateTime? yourBirthday = null;
DateTime? myBirthday = yourBirthday.Value;


If you think this code snippet is purely hypothetical, think twice. We've come accross half a dozen of posts on forums with similar code posted by programmers having trouble with nullable types.

As you may guess, the code above is correct C# syntax-wise and as expected the compiler does not complaint. Alas, a runtime error is guaranteed when the above code is reached. More specifically, you will get [InvalidOperationException: Nullable object must have a value.]

In MSDN we read what the Value property is:

The value of the current Nullable<T> object if the HasValue property is true. An exception is thrown if the HasValue property is false.

Let's quickly fix the above code. Initially, you may think about the following code:

DateTime? yourBirthday = null;
DateTime? myBirthday = yourBirthday.HasValue? yourBirthday.Value : null;


As soon as you press F5 in Visual Studio, the compilator starts complaining that Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'null'. Finally, the fixed code below compiles just fine and gives you no runtime exception.

DateTime? yourBirthday = null;
DateTime? myBirthday = yourBirthday.HasValue? yourBirthday.Value : (DateTime?) null;


Happy coding!

How to Add Existing Folder to Visual Studio


Visual Studio has a nice feature to add existing files to a project and the process if simple and straightforward. What about adding an existing folder to a project? This is especially useful if you accidentally remove a folder from a project. A typical action done by developers in this case is to create a new folder in the project, add existing files there, delete the existing folder and then rename the new folder.

Visual Studio has functionality to easily add existing folders to the project. However, this functionality is not visible. In other words, there is no "Add Existing Folder..." menu item neither in the main menu, nor in the project's shortcut menu.

To add an existing folder to Visual Studio project first click the Show All Files button in Solution Explorer. This will show all files and folder even if they are excluded from the project. Now just right click a particular folder and select the Include In Project menu item.

For your convenience, please have a look at the screen shot. We have circled in red the Show All Files button and the folder that we would like to include.

How to Get the Unique ID for the Last Inserted Row in MySQL/PHP

If you insert a new row in a table that contains AUTO_INCREMENT field, oftentimes you may be interested in getting the value of the auto incremented field. This is a very common scenario if the value of the auto incremented field acts as a foreign key in other tables. There are plenty examples. For example, if you have Orders table, it most likely contains auto incremeted Id field and OrderItems table that contains OrderId field. A common scenrario is to insert a row in the Orders table, obtain the value of the Id field and then use it for the OrderId field in the OrderItems table.

In MySQL and PHP this is extremely easy. All you need to do is to call the mysql_insert_id() function.

Many developers are worried about concurency issues. Suppose the current value of the auto incremented field is 1001. In other words, the next order id should be 1002 and so on. Further, suppose that User A and User B simultaneously place orders and thus insert records in the Orders table. You may wonder what mysql_insert_id() will return.

According to the MySQL documentation, the mysql_insert_id() function works on a per-connection basis. In other words, User A will get 1002 and User B will get 1003. So, in contrary to the false assumption everything will be fine.

For completeness of the tip, please note that you can also obtain the value of the auto incremented field by executing a SELECT LAST_INSERT_ID() statement with mysql_query() function and retrieving the value from the result set returned by the statement. However, in our opinion the mysql_insert_id() function is easier.

For a detailed description of the above mentioned function, please visit the MySQL documention page: http://cut.io/ELY5

Follow us on Twitter

We are glad to announce that from now on you can follow our team and particularly this blog on Twitter. We will be updating our Twitter feed when new posts are published. Our Twitter feed will also serve for general news from P2PSYS Development Studio.

Stay tuned and follow us on Twitter at http://twitter.com/p2psys