Jump to content

*new to this fourm* php SQL search script


Recommended Posts

Hi guys,

 

Im trying to make a sql query where it searches for the fields i select from a form.

The problem is i have been using the "like" operator so i can leave the search field black in the form if needs be. But this has mad a problem as it returns other results that are LIKE and not what i want.

 

the only why i can think of doing this is to rebuild lots of statements with if isset, but thats not very good programing,

the only other thin i can think of is to use if isset and then have it dynamically build the sql statement, but i don't know how to do this.

 

can anyone help me please.

 

$sql04 = "SELECT * FROM payments WHERE companyID LIKE '%".$_GET['company']."%' AND monthNo LIKE '%".$_GET['month']."%' AND salesmanID LIKE '%".$_GET['salesman']."%' AND stageID LIKE '%".$_GET['stage']."%'";

Link to comment
https://forums.phpfreaks.com/topic/202509-new-to-this-fourm-php-sql-search-script/
Share on other sites

dynamically build the sql statement

 

Oh its not that bad:

 


$fields=array("companyID" => "company", "monthNo" => "month", "salesmanID" => "salesman", "stageID"=>"stage");
$sql04="SELECT * FROM payments ";

foreach ($fields as $key => $arg)
{
if(isset($_GET[$arg])
$sql04 .= "WHERE $key= {$_GET[$arg]} AND";
}
$sql04=rtrim($sql04, " AND");

yep, it repeats the where clause when it shouldn't.  I suck.

 


$fields=array("companyID" => "company", "monthNo" => "month", "salesmanID" => "salesman", "stageID"=>"stage");
$sql04="SELECT * FROM payments WHERE 1";

foreach ($fields as $key => $arg)
{
if(isset($_GET[$arg])
$sql04 .= " AND $key= {$_GET[$arg]}";
}

 

Is there a better way?

 

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.