0

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

Edited by gilgil2

4
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by diafol
0

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']))
0

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

3

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'");
Votes + Comments
Agree, % is only used for LIKE
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.