Ah, shi- WTF?
Smaller PHP Code
Back when I first started writing in PHP and integrating mySQL databases, the tutorials I found were often all similar, almost as if copied and pasted between websites. I know there are only so many ways to skin a cat, as the saying goes, but what if you want something a bit more optimized? Today, I was making a ‘latest post’ page for the site with which I could alert people to updates through a forum signature for example. As I started typing out the trusty old mysql_connect command in PHP, I decided to do some experimenting.
The first example on PHP.net uses this code to teach you how to use the mysql_connect function:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
// Changed from mysql_close() to mysql_select_db() for completeness
mysql_select_db('foo', $link);
Ok, 6 actual lines, that’s not bad; it works at least. It just seems to take up a bit too much room for establishing a connection. Let’s try a bit of streamlining. We don’t actually need the if… statement at all, even if we want to do something on the event that we don’t connect. So if we change the structure a bit:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('foo', $link);
3 lines. Much better. Seeing as we still need the variable $link for connecting to the database, we still need to assign it, even though we aren’t checking it for a connection. Although we aren’t checking the connection, the “or die” statement means that the script will fail with an error message if no connection is made, rather than give what could be a much more unfriendly message. We could also add one for the mysql_select_db function too, in case the database is unavailable for some reason.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error());
mysql_select_db('foo', $link) or die ('Could not connect: ' . mysql_error())
I’ve now removed the comment saying that we are connected, it’s not needed and almost instantly deleted by anybody that knows what they’re doing; you don’t want end-users to see you just connected to a database do you? So that’s 2 lines. Now, the reason I was thinking about shortening code down today is because I had a revelation about using return values from functions. We know that $link is a “MySQL link identifier“, which is exactly what is needed in the mysql_select_db function as the second parameter. So rather than return it to a variable and pass that, why not pass the function directly?
mysql_select_db('foo', mysql_connect('localhost', 'mysql_user', 'mysql_password')) or die ('Could not connect: ' . mysql_error())
And there we have it, 1 line instead of 6. We also have the added bonus of only having one “or die” statement; mysql_error() means it will always tell us the exact problem rather than a generic error message. This code shortening technique can be employed in more than just this small snippet however. Back to the original idea, this helped me out doing my latest post page as I turned this:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foo", $link) or die("Server or Database connection failed");
$result = mysql_query('SELECT * FROM `posts` WHERE post_status="publish" and post_name <> "about" ORDER BY ID DESC LIMIT 1');
$row = mysql_fetch_array($result);
$result2 = mysql_query("SELECT display_name FROM `users` WHERE ID='".$row['post_author']."'")
$row2 = mysql_fetch_array($result2);
$date = explode(" ", $row['post_date']);
$date2 = explode("-", $date[0]);
echo $row['post_title']."<br/>By " . $row2[0] . " on " . $date2[2]."-".$date2[1]."-".$date2[0];
into this:
mysql_select_db("foo", mysql_connect('localhost', 'mysql_user', 'mysql_password')) or die("Server or Database connection failed");
$row = mysql_fetch_array(mysql_query('SELECT * FROM `posts` WHERE post_status="publish" and post_name <> "about" ORDER BY ID DESC LIMIT 1'));
$row2 = mysql_fetch_array(mysql_query("SELECT display_name FROM `users` WHERE ID='".$row['post_author']."'"));
$date = explode(" ", $row['post_date']);
$date2 = explode("-", $date[0]);
echo $row['post_title']."<br/>By " . $row2[0] . " on " . $date2[2]."-".$date2[1]."-".$date2[0];
Feel free to use the method of grabbing the latest post. There are some potential problems with using this sort of structure for your code. Mainly, it might make it harder to determine the cause of problems if an error suddenly crops up. It’s obviously just a case then of expanding the code out. Luckily the PHP error messages are fairly informative when you get used to them, which should make it easier. Also, make sure that if you are adapting code that’s already written, that your ensure special characters and the like are correct. A semi-colon after mysql_connect, but before the end of the line, could have dire consequences for example. It will tell you there is an unexpected “;” on line x, which could mean looking through quite a bit of code. Finally, I would like to say this is probably only a good idea in an already implemented page, not one in development or being offered as a download to other developers.
| Print article | This entry was posted by Spunky on December 27, 2009 at 9:18 pm, and is filed under Web Development. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |