mysql_free_result(): The Right Way

NOTE: This method can also be applied to the MySQL Improved Class. Just make the necessary changes to the functions called.

Imagine this scenario: You have a website that consists of a header.php file, a footer.php file, and a file for every page of content. You probably can guess what the header.php file and the footer.php file contain. Your header.php file and footer.php file is called on every page. Because they include necessary tags and other code that you’ll need on every page. So a sample file might contain the following:

<?php include_once("header.php"); ?>

<!-- Page Content Goes Here! -->

<?php include_once("footer.php");
?>

In your header.php file you have something like this:

$mysql = mysql_connect(MYSQL_HOST, MYSQL_USERNAME, MYSQL_PASSWORD);

<-- Header HTML Here -->

In your footer.php file you have something like this:

<-- Footer HTML Here -->

<?php
mysql_free_result($result);
mysql_close($mysql);
?>

The problem is that you might not query MySQL on every page. If you don’t PHP will give a error telling you that the $result variable was never used! This can be counteracted with a simple if() and isset() statement.

<?php
if(isset($result)) {
mysql_free_result($result);
}
?>

Simplistic and effective! How much better does it get? It will only use the mysql_free_result() function when needed. Increasing performance and one less error.

This entry was posted on Sunday, October 12th, 2008 at 12:30 am and is filed under Technology, Web Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply