Jump to content

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?

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.