Archive for the 'PHP' Category


PHP vs Perl 0

Being my first real post, I thought I would show something that I really benefitted me by moving to PHP from Perl, but that ultimately helped me whenever I maintained Perl code.

In pulling data from a MySQL database for example, one might use the following PHP code:

1
2
3
4
5
6
7
// MySQL database connection code previously defined
$statement = mysql_query("select first_name, last_name from users");
 
while ($user_data = mysql_fetch_assoc($statement))
{
	echo "First Name: " . $user_data['first_name'] . " Last Name: " . $user_data['last_name'] . "\n";   
}

Line 2: this is our MySQL query.
Line 4: our while loop that goes through each row of returned MySQL date. mysql_fetch_assoc puts the MySQL data into an associative array. (see array detail below).
Line 6: here we echo everything out to the browser.

This would obviously pull all the first and last names from a users table, and print them out nice and neatly. Notice that I used $user_data['first_name'] and user_data['first_name'] to pull the first name and last name, respectively. User data is built like so:

Array
(
    [first_name] => John
    [last_name] => Doe
)

So when I code $user_data['first_name'], what I’ll get is “John”.

The same code in Perl might go something like this:

1
2
3
4
5
6
7
8
9
# $dbh, or the MySQL database connection, was defined early in the code
my $statement = "select * from users";
my $sth = $dbh->prepare($statement) or die "can't prepare the statement";
my $rv = $sth->execute or die "can't execute the query: $sth->errstr";
 
while (my $user_data = $sth->fetchrow_hashref())
{
	print "First Name: " . $user_data->{'first_name'} . " Last Name: " . $user_data->{'last_name'} . "\n";   
}

Line 2: our MySQL query.
Line 3: we prepare the statement for execution.
Line 4: we execute the query, calling die if there is an error.
Line 6: similar to the PHP while, we put the MySQL data into a Perl hash, very much like a PHP associative array.
Line 8: here we print it all out.

The output of this code is exactly the same as the PHP code. Sadly, it took me learning PHP to realize that you could even do this with MySQL data, and so … for many years I annoyingly coded my MySQL data in perl using indexes ($user_data[0] instead of $user_data->{‘first_name’}).

Anyway, I hope this helps understand how to make Perl do what PHP does so easily. Enjoy!