Jump to content

If statement within if statement?


Chris.P

Recommended Posts

I've written the following code that grabs the meta description set in the MySQL database. Basically what I want to do it check the $metadescription variable and if it's empty run another query to put a different piece of information from the database in there. It seems like another if statement would be needed?

 

function metadescription() {

	global $db;

	//checks if it's our category page
	if(isset($_GET['cat_id'])) {

	$cat_id = mysql_real_escape_string($_GET['cat_id']);
	$query = "SELECT * FROM categories WHERE cat_id = '$cat_id'";
        $result = $db->query($query);
	$result = $db->fetchrow($result);
        $metadescription .= $result['cat_meta_description'];

	}

	return htmlentities($metadescription);

}

 

 

Link to comment
https://forums.phpfreaks.com/topic/238958-if-statement-within-if-statement/
Share on other sites

First, never, ever, ever use 'global'.  Parameters to functions should be passed in via the functions' argument list.  That's why it's there.  Functions have a public interface - their names and what parameters should be passed in.  'Global' adds an implicit requirement which is hidden to the system at large, since the requirement is not a part of the function's interface, and ties the function it's used in to the larger context of the system, which negates one of the points of using functions to begin with - modularity.

 

I don't know where beginners get the idea to pass parameters in via 'global', but it's the absolute wrong way to do it.  Find a better tutorial site/book/instructor.

 

Second, with all that said, adding another if-conditional is easy:

 

function metadescription($db)
{
   //checks if it's our category page
   if (isset($_GET['cat_id']))
   {		
      $cat_id = mysql_real_escape_string($_GET['cat_id']);
      $query = "SELECT * FROM categories WHERE cat_id = '$cat_id'";
      $result = $db->query($query);
      $result = $db->fetchrow($result);
      $metadescription .= $result['cat_meta_description'];

      if (empty($metadescription))
      {
          // run additional query and do stuff
      }
   }

   return htmlentities($metadescription);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.