Jump to content

Using Mysql To Search A Database


gsingh2011

Recommended Posts

I have some php code that searches an sql database. Originally the user could search a keyword and narrow the results by the year and month of the article. This is the code I used,

if($year == "all"){		if($month2 == "all"){			$result = mysql_query("SELECT * FROM Files WHERE Title ='".$query."'"); 		} else {			$result = mysql_query("SELECT * FROM Files WHERE Title ='".$query."' AND Month = '".$month2."'"); 		}	} else if ($month2 == "all"){		$result = mysql_query("SELECT * FROM Files WHERE Title ='".$query."' AND Year = '".$year."'"); 	} else{		$result = mysql_query("SELECT * FROM Files WHERE Title ='".$query."' AND Month = '".$month2."' AND Year = '".$year."'"); 	}

"all" was the default value, and I had to make all of these if statements to take care of all the possibilities of the user selecting all vs. selecting an actual month or year. The problem is now that I have to add two more options, subject and author. If i do this in the same method I'm going to have tons of if statements... Is there a more efficient way to add these two options in?

Link to comment
Share on other sites

Not sure if there's a better, more efficient way but I think there's a cleaner way:

$sql = "SELECT * FROM Files WHERE (Title = '".$query."'";if ($month != "all) {	 $sql.=" AND Month = '".$month2."'";}if ($year != "all") {	 $sql.=" AND Year = '".$year."'";}$sql.=")";$result = mysql_query($sql);

That way you can just add another if statement for your subject and author without using a complicated if...else structure.

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...