How to Check that a PHP Variable is a Mysql Resource

By | October 15, 2010

When you create something related to mysql, it is always important to verify that your variables contain the things you expect. Here are some code lines that will allow you to verify whether your variables are mysql resources or not.

The first way to verify that we deal with the resource is to check it with is_resource php function. Here is the sample form PHP official website:

< ?php $db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass'); if (!is_resource($db_link)) { die('Can't connect : ' . mysql_error()); } ?>

When we know that our variable contain a resource, we need to ensure that it is a mysql resource. Another PHP function will help us to do this. It’s get_resource_type().

< ?php $c = mysql_connect(); $restype=get_resource_type($c); if (stristr($restype, "mysql")) echo "OK"; ?>

This will check the resource type and will return OK if it is a mysql resource. So the final check will look like:

if (is_resource($db_link) && stristr($db_link, “mysql”)) echo “OK”;

This way you will be sure that you have a mysql resource associated with your variable.