Jump to content

[SOLVED] search function


agge

Recommended Posts

This is my code..

 

search.php

<?php 
if (isset($_POST['Search'])){

some code...

}
?>

<form action="http://localhost" method="post" target="_self">
<input type="text" name="value_1" />
<input type="text" name="value_2" />
<input type="text" name="value_3" />
<input type="text" name="value_4" />
<input type="text" name="value_5" />
<input name="Search" type="button" value="Search" />
</form>

If user only fill in values into value_1, value_2 and value_5 this time I get this URL

I get all this in the url like this: http://localhost/search.php?value_1=d&value_2=34&value_3=&value_4=&value_5=Spring

 

get.php

<?php 
$value_1 = $_GET['value_1'];
$value_2 = $_GET['value_2'];
$value_3 = $_GET['value_3'];
$value_4 = $_GET['value_4'];
$value_5 = $_GET['value_5'];
?>

 

this I get from my URL that value_1=d, value_2=34 but value_3='empty' and value_4='empty' value_5=Spring

 

then to my question:

 

I have query that will search through my db WHERE value_1='$value_1' AND value_2='$value_2' AND value_3='$value_3' AND value_4='$value_4' AND value_5 ='$value_5'

 

I cant search for value_3 and value_4 because they are empty.

 

Anyone who has some solution to solve this?

 

 

Link to comment
https://forums.phpfreaks.com/topic/45299-solved-search-function/
Share on other sites

<?php

$query = "SELECT col1, col2 FROM tbl WHERE 1";

if ($_GET['value_1'] != ""){
   $query .= " AND value_1 = '$value_1'";
}

if ($_GET['value_2'] != ""){
   $query .= " AND value_2 = '$value_2'";
}

//Keep going with each value

$result = mysql_query($query);

?>

 

You can just keep continuing like that.

 

 

Change your form to use an array for the seach name:

<form action="http://localhost" method="post" target="_self">
<input type="text" name="value[]" />
<input type="text" name="value[]" />
<input type="text" name="value[]" />
<input type="text" name="value[]" />
<input type="text" name="value[]" />
<input name="Search" type="button" value="Search" />
</form>

Then you can easily set up the "where" clause like this:

<?php
$tmp = array();
for($i=0;$i<count($_POST['value']);$i++)
     if (strlen(trim(stripslashes($_POST['value'][$i]))) != 0)
            $tmp[] = 'value_' . $i . " = '" . mysql_real_escape_string($_POST['value'][$i]) . "'";
if (!empty($tmp))
    $wc = ' where ' . implode(' AND ',$tmp);
echo $wc; // debuging line to see what you've gotten
?>

 

Ken

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.