Hi, I am trying to query a MySql database based on which search fields are filled in and ignoring those that aren't. I have only got as far as the first part and it isn't working, could anyone tell me why?

It doesn't seem to be finding anything in the database

if ((isset($_POST['band'])) && (!isset($_POST['day'])) && (!isset($_POST['month'])) && (!isset($_POST['year'])) && (!isset($_POST['location'])))
{
    $result = mysql_query("SELECT * FROM gigs WHERE band LIKE '%$band%'");  


    while($row = mysql_fetch_array($result)) 
    { 
        $page = sprintf( "<a href='http://www.example.com/%s'>%s</a>" , $row['PageName']  , $row['band']  ) ;
        echo 'Band Name:  '; 
        echo $row['band'] ." " . " " . $row['day'] . " " . $row['month'] . " " . $row['year']. " " . $row['Genre'];
        echo $page;  
        echo "<br />";
    }

}

else echo 'No gigs found' ;

Thanks in advance

Hi,

add this just above $result

 $band = $_POST['band'];

Or you can just put your $_POST['band'] variable into your query without assigning it to another variable.

Either way I would also suggest putting the variable in speech marks to prevent problems:

$result = mysql_query("SELECT * FROM gigs WHERE band LIKE '%'".$band."'%'");

You can also tidy up your if statement as you don't need so many parentheses (makes it easier to read):

if (isset($_POST['band']) && !isset($_POST['day']) && !isset($_POST['month']) && !isset($_POST['year']) && !isset($_POST['location']))

Thanks for the responses, with your help and using empty() I have got it sorted, now I have a different problem though.

If I search for data that is in database of one of the conditions it doesn't find anything, I think the problem is to with this part:

$result = mysql_query("SELECT * FROM gigs WHERE band LIKE '%".$_POST['band']."%' AND day='%".$_POST['day']."%' AND month='%".$_POST['month']."%' AND year='%".$_POST['year']."%'");

The day and year are numerical and month is text. I have tried removing ' ' from the numerical ones but that did work, or I have done it wrong. Any ideas?

Thanks

Member Avatar for diafol

Why have you got '%' surrounding the variables? You only need those for LIKE, not '='. BTW storing dates in this way is very cumbersome - why not just use a date field (Y-m-d) or a unix timestamp (integer)? Also backtick your tables and fields and clean your inputs - never use raw POST vars in an sql statement:

$result = mysql_query("SELECT * FROM `gigs` WHERE `band` LIKE '%$band%' AND `day`='$day' AND `month`='$month' AND `year`='$year'");

Ideally you'd want something like this:

$result = mysql_query("SELECT * FROM `gigs` WHERE `band` LIKE '%$band%' AND `date`= '$date'");
commented: Agree, % is only used for LIKE +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.