473,503 Members | 2,046 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help PHP Search database by selecting checkbox

greensleeves
5 New Member
Hi, Im a newbie to PHP and I'm wondering if someone could help me out with this
Tryng to search out products from a database by clicking a checkbox option

for instance if description contains the word "bluetooth" and "MP3"
Expand|Select|Wrap|Line Numbers
  1. <input type="checkbox" value="bt" />Bluetooth <br /> 
  2. <input type="checkbox" value="cs" />Card slot <br /> 
  3. <input type="checkbox" value="mp3" />MP3 player <br /> 
  4.  
here is my database
Expand|Select|Wrap|Line Numbers
  1. $query = "SELECT id, manufacturer, item_number, description FROM $table_name 
  2. $result = @mysql_query ($query) 
  3.  
Here is my table layout
Expand|Select|Wrap|Line Numbers
  1. echo '<table> 
  2. <tr> 
  3. <td class="layout"><b><a href="' . $link1 . '">Manufacturer</a></b></td> 
  4. <td class="layout"><b><a href="' . $link2 . '">Item Number</a></b></td> 
  5. <td class="layout"><b><a href="' . $link3 . '">Description</a></b></td> 
  6. </tr> 
  7. '; 
  8.  
  9. // Fetch and print all the records. 
  10. $bg = '#eeeeee'; // Set the background color. 
  11. while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
  12. $bg = ($bg=='#eeeeee'? '#ffffff' : '#eeeeee'); // Switch the background color. 
  13. echo '<tr bgcolor="' . $bg . '"> 
  14. <td class="layout_nowwrap">' . $row['manufacturer'] . '</td> 
  15. <td class="layout">' . $row['item_number'] . '</td> 
  16. <td class="layout">' . $row['description'] . '</td> 
  17. </tr> 
  18. '; } 
  19.  
  20. echo '</table>'; 
  21.  
just in case your wondering I also set cases for sorting through colums
Expand|Select|Wrap|Line Numbers
  1. $link1 = "{$_SERVER['PHP_SELF']}?sort=mfa"; // manufacturer 
  2. $link2 = "{$_SERVER['PHP_SELF']}?sort=ina"; // item_number 
  3. #and so on.... 
  4.  
  5. // manufacturer case 
  6. case 'mfa': 
  7. $order_by = 'manufacturer DESC, item_number DESC'; 
  8. $link1 = "{$_SERVER['PHP_SELF']}?sort=mfd"; 
  9. break; 
  10. case 'mfd': 
  11. $order_by = 'manufacturer ASC, item_number ASC'; 
  12. $link1 = "{$_SERVER['PHP_SELF']}?sort=mfa"; 
  13. break; 
  14.  
hope someone can help me with this... thanks
Oct 25 '07 #1
9 4006
Lumpy
69 New Member
Well, by far there are many people on this site that are way better php programmers than myself, but I will see what I can do to help you out. I have gotten lots of help here and I want to try to give some back, so here it goes.

Your form, the input boxes, don't have names and I am unsure if you are using POST or GET with the form. In my example I am going to use POST. The other thing I am unsure of is if the same page is going to handle the forms action, but I am going to assume so. With that being said, you need to add a little to your checkboxes on the form, mainly the form tags telling the form what to do when submitted, and the submit, or in this case search button. So it should look something like this...

Expand|Select|Wrap|Line Numbers
  1.   <form action="page.php" method="post">
  2.     <input type="checkbox" value="bt" name="bt"/>Bluetooth <br />
  3.     <input type="checkbox" value="cs" name="cs"/>Card slot <br />
  4.     <input type="checkbox" value="mp3" name="mp3"/>MP3 player <br />
  5.     <input type="submit" value="search"/>
  6.   </form>
  7.  
The forms action is set to whatever the page is the will process the search, I just put "page.php" in there and the method is set to post. I added in the name attribute of the checkbox inputs and put a submit button on the bottom that says "search".

Than on the page that will handle this request, you will need to do something like the following with your php to build the rest of your SQL statement to get the right data from your query. Try to follow me here, there might be a better way, but this is how I saw the solution...

The first thing I did was move the search terms from the POST array to a new array called searchterm going something like this...

Expand|Select|Wrap|Line Numbers
  1. foreach ($_POST as $var) {
  2.  $searchterm[] = $var;
  3. }
  4.  
  5.  
Then you want to count the number of variables in the searchterm array and begin building the rest of your SQL statement. I also added in another variable in the if statment to see if we need to add the AND(it could be OR in your case as well, I don't know) into the SQL statement for searching for results. The if statement will add the AND for each time through the while statement after the first time through. This code would go after where you already stated the first part of your $query variable, because we want to add on to it.

Expand|Select|Wrap|Line Numbers
  1.  
  2. $c = count($searchterm);
  3. ///check to see that there is a search term and add the WHERE into the SQL
  4. if ($c > 0) {
  5.   $query .= " WHERE";
  6. }
  7.  
  8. $i = 1;
  9.  
  10. while ($c-- > 0) {
  11. ///an if statement to check and see if we should add the "AND" into the query 
  12.  if ($i > 1) {
  13.    $query .= " AND";
  14.  }
  15. ///add in the search term or value into the query
  16. $query .= " fieldname = " . $searchterm[$c];
  17. $i++;
  18. }
  19.  
  20.  
Something like that should work, although the SQL syntax may need a little tweaking, I am not sure with the SQL part. it might need to be something like...

Expand|Select|Wrap|Line Numbers
  1.  $query .= " fieldname = \' " . $searchterm . " \' ";
  2.  
anyways, I hope this helps.
Oct 25 '07 #2
greensleeves
5 New Member
Thank you for the reply. This page is handling it SELF i'm not sure if this is good practice but yeah thats what im tryn to do. Could u pls explain how I would call the tags and have the query search out and match these values. Would i need to set and call a function? Also how would i set these search filters on various fieldnames

<?
include ('./includes/header.html');

require_once ('./mysql_connect.php');

foreach ($_POST as $var) {
$searchterm[] = $var;
}

// query.
$query = "SELECT id, manufacturer, item_number, description FROM $table_name ";
$c = count($searchterm);
///check to see that there is a search term and add the WHERE into the SQL
if ($c > 0) {
$query .= " WHERE";
}

$i = 1;

while ($c-- > 0) {
///an if statement to check and see if we should add the "AND" into the query
if ($i > 1) {
$query .= " AND";
}
///add in the search term or value into the query
$query .= " description = " . $searchterm[$c];
$i++;
}

$query .= " description = \' " . $searchterm . " \' ";
$query .= "ORDER BY manufacturer ASC ";

$result = @mysql_query ($query); // Run the query.

// checkbox
echo '<form action="page.php" method="post">
<input type="checkbox" value="bluetooth" name="bluetooth"/>Bluetooth <br />
<input type="checkbox" value="mp3" name="mp3"/>MP3 <br />
<input type="checkbox" value="video" name="video"/>Video <br />

<input type="submit" value="search"/>
</form> ';

// Table header.
echo '<table> ';

$bg = '#eeeeee'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color.
echo '<tr bgcolor="' . $bg . '">
<td>' . $row['manufacturer'] . '</td>
<td>' . $row['item_number'] . '</td>
<td>' . $row['description'] . '</td>
</tr>
';
}
echo '</table>';

mysql_free_result ($result);
mysql_close(); // Close the database connection.

include ('./includes/footer.html');
?>

thanks again for your help
Oct 26 '07 #3
Lumpy
69 New Member
I am not sure if I am understanding what your asking, but let me take a shot at answering it. You want to know how to call the tags or items and then have the query search for it. This is dependent on what the user clicks as far as what they are going to search for. So if they click mp3, you want the query to search for and return rows of products in the mp3 category. Right now the code is going to build that query for you. One thing I did notice is that the query is going to check the field named description. I am not sure off the top of my head how to get a query to search through the whole description of a product to search for 'mp3', but I would check the mysql manual available on the website. Another option would be to add a field to your table possibly named category and use that field to match the search with, or create another table and join them together.

The query right now when someone clicks an option to search, such as mp3 is going to take that information and search for and return rows "WHERE description = mp3", that is why we put the WHERE in the query. Now if the description field is a product description, it will probably return 0 rows because each row will most likely have more than just "mp3" as a description, this is why I suggested adding in the category field and search that field.

If no search is entered by the user, the query should go through and pull all the rows from the table, because it will skip adding in the "WHERE" clause of the query. You will also, most likely want to change the "AND" to an "OR", so when a search is done with bt and mp3, your query will return both types of products. The "OR" will have the query pull a row if the description is mp3 OR bt.

For the second question, if you want to set the search to different fieldnames, then I would look into creating a data abstraction layer. This is a class that will handle data retrieval and you could just pass the field name to search into the function within the class object and search that fieldname with your query. There is an excellent article written by Motoma on this exact topic... http://www.thescripts.com/forum/thread632487.html. That should give you a good idea how to accomplish this.

One other thing, I removed a line from your code. The line I removed was the last line I had in my suggestion, and I put it not because it needed to be there but that might be what is needed to get the SQL syntax correct in place of this line...$query .= " description = " . $searchterm[$c];

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. include ('./includes/header.html');
  3.  
  4. require_once ('./mysql_connect.php');
  5.  
  6. foreach ($_POST as $var) {
  7.  $searchterm[] = $var;
  8. }
  9.  
  10. // query.
  11. $query = "SELECT id, manufacturer, item_number, description FROM $table_name ";
  12. $c = count($searchterm);
  13. ///check to see that there is a search term and add the WHERE into the SQL
  14. if ($c > 0) {
  15.   $query .= " WHERE";
  16. }
  17.  
  18. $i = 1;
  19.  
  20. while ($c-- > 0) {
  21. ///an if statement to check and see if we should add the "AND" into the query 
  22.  if ($i > 1) {
  23.    $query .= " OR";
  24.  }
  25. ///add in the search term or value into the query
  26. $query .= " description = " . $searchterm[$c];
  27. $i++;
  28. }
  29.  
  30. $query .= "ORDER BY manufacturer ASC ";        
  31.  
  32. $result = @mysql_query ($query); /// Run the query.
  33.  
  34. /// checkbox
  35. echo '<form action="page.php" method="post">
  36. <input type="checkbox" value="bluetooth" name="bluetooth"/>Bluetooth<br />
  37. <input type="checkbox" value="mp3" name="mp3"/>MP3<br />
  38. <input type="checkbox" value="video" name="video"/>Video<br />
  39. <input type="submit" value="search"/>
  40. </form> ';
  41.  
  42. /// Table header.
  43. echo '<table> ';
  44.  
  45. $bg = '#eeeeee'; /// Set the background color.
  46. while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  47.     $bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); /// Switch the background color.
  48.     echo '<tr bgcolor="' . $bg . '">
  49.         <td>' . $row['manufacturer'] . '</td>
  50.         <td>' . $row['item_number'] . '</td>
  51.         <td>' . $row['description'] . '</td>
  52.     </tr>
  53.     ';
  54. }
  55. echo '</table>';
  56.  
  57. mysql_free_result ($result);     
  58. mysql_close(); /// Close the database connection;
  59.  
  60. include ('./includes/footer.html');
  61. ?>
  62.  
Hope this helps.
Oct 27 '07 #4
greensleeves
5 New Member
Nice... Thanks for pointed me in the right direction. With a lil tweaking I was able to search through the description field and display the results just as I wanted... Thank you so much for your help :)
Oct 27 '07 #5
Lumpy
69 New Member
Nice... Thanks for pointed me in the right direction. With a lil tweaking I was able to search through the description field and display the results just as I wanted... Thank you so much for your help :)
No Problem! I'm glad you were able to get it working and I was able to be of some help to you. :D
Oct 28 '07 #6
greensleeves
5 New Member
I would like to take this a little further now hope you can help… So this is the thing I want to sort through the results query’d on checking. I set up cases to handle the table sorting but when I click the results are query’d back to the original all not just the filtered results

How can I keep and sort through the filtered results

$link2 = "{$_SERVER['PHP_SELF']}?sort=mfa"; // manufacturer
$link3 = "{$_SERVER['PHP_SELF']}?sort=ina"; // item_number
$link7 = "{$_SERVER['PHP_SELF']}?sort=dna"; // description

// Determine the sorting order.
if (isset($_GET['sort'])) {

switch ($_GET['sort']) {
case 'mfa':
$order_by = 'manufacturer DESC, item_number DESC, color DESC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=mfd";
break;

case 'mfd':
$order_by = 'manufacturer ASC, item_number ASC, color ASC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=mfa";
break;
// repeats so cut out for space

default:
$order_by = 'manufacturer ASC, item_number ASC';
break;
}

$sort = $_GET['sort'];
} else { // default sorting order.
$order_by = 'manufacturer ASC, item_number ASC';
$sort = 'mfd';
}

// Here's the table
echo '<table>
<tr>
<td><b><a href="' . $link2 . '">Manufacturer</a></b></td>
<td><b><a href="' . $link3 . '">Item Number</a></b></td>
<td><b><a href="' . $link7 . '">Description</a></b></td>
</tr>
';

// Fetch and print all the records.
$bg = '#eeeeee'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eeeeee'? '#ffffff' : '#eeeeee'); // Switch the background color.

echo '<tr bgcolor="' . $bg . '">
<td>' . $row['manufacturer'] . '</td>
<td>' . $row['item_number'] . '</td>
<td>' . $row['description'] . '</td>
</tr> ';
}
echo '</table>';

also how would I keep the checkboxes checked on submiting right now they reset to off on _POST
any help??
Oct 28 '07 #7
Lumpy
69 New Member
If I am getting your question, by keeping the box checked after the user checks it, that would solve your problem of the query returning to the original query. Correct?

If that is the case, you will need to add in a little php script when drawing your form's check boxes, to see if they were checked before, and if they were then you would add in 'checked="checked" to the html checkbox tag.

Expand|Select|Wrap|Line Numbers
  1.  
  2. if (isset($_POST['mp3'])) {
  3. echo '<input type="checkbox" value="mp3" name="mp3" checked="checked"/>';
  4. } else {
  5. echo '<input type="checkbox" value="mp3" name="mp3"/>';
  6. }
  7.  
I don't know that there would be a better way to do it, but if I think of it I'll let you know.

PS putting the "CODE" tags around your code will make it post a little better and easier to read. Before your first line of code you would want to enclose CODE=php within [ ] and after the last line of code, you want to enclose /CODE within [ ].
Oct 29 '07 #8
greensleeves
5 New Member
Thanks again for your reply. Well although this did help keep the checkboxes checked on POST it didn't solve the problem of the query resetting back when the sort link is selected. When the sort link is selected the checkboxes go back to being unchecked :( Any further solutions for this??
Oct 29 '07 #9
Lumpy
69 New Member
I get what your saying now. For some reason it didn't click what you were asking before. I can see how that isn't going to help.

To get it to do this, can you change your forms method to "GET"? and make a few changes in your code, something like...


The first change is the foreach statement that moves your GET variables to the $searchterm array...
Expand|Select|Wrap|Line Numbers
  1. foreach ($_GET as $var) {
  2.  if (!$_GET['sort']) {
  3.  $searchterm[] = $var;
  4.  }
  5. }
  6.  
The next change is going to be how the query gets the order by instructions. This will have to come after your switch statement but before the query is ran.

Expand|Select|Wrap|Line Numbers
  1. $query .= "ORDER BY" . $order_by . "';";
  2.  
And then you will have to have php build you links, something like this so they will have all the right info in them...

Expand|Select|Wrap|Line Numbers
  1. $link = "{$_SERVER['PHP_SELF']}";
  2. foreach ($_GET as $key => $var) {
  3.     $link .= "?" . $key . "=" . $var;
  4. }
  5.  
it will take a little tweaking to work the way you want it, but by using a GET method with your form, you can just keep all the variables right in the url and keep reusing them as you continue to change the appearance. Give this a shot and I think you can get it how you want it...
Oct 30 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

3
2438
by: Adam Toline | last post by:
In reference to the following: http://www.bellecose.com/form.htm At the top of each column there is a box for "All". When one is checked I need to check all of (and only) those boxes...
0
1977
by: Faybert | last post by:
Hello, and Thanks in advance for any light you might shed on my troubles. I'm trying to setup a series of checkboxes, or a checkboxlist to control the results that are shown on a gridview...
0
1499
by: rahulash | last post by:
I have a JSP showing data retreived from a database. This JSP is styled based on an XSL. The database returns data like student name, course, student remarks. I intend to add a checkbox which...
4
2536
by: ramapv | last post by:
can i highlight a checkbox from a group of checkbox with particular name which is given as a search key. I am having a list of checkboxes and i have to select some of them and form a group.but i'm...
0
5518
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted...
3
2995
by: cuties | last post by:
Hi all.... i'm very new to this programming language. i'm required to fulfill this task in the company i'm doing my practical. i hope i can get guide for my problem... Here is the script i...
4
2728
by: khyati30 | last post by:
hello , here , i have arised problem in php & mysql . i have one form which has 3 checkboxes .if i m selected checkbox then the radiogroup is enable and i m selected one value. if i m...
2
4868
by: scottSD | last post by:
Hi everyone. this is my first post here, but i've found quite a bit of great information from reading the forums in the past. i'm not sure if what i'm trying to do is possible or not, but here it...
32
2752
by: =?Utf-8?B?U2l2?= | last post by:
I have a form that I programmatically generate some check boxes and labels on. Later on when I want to draw the form with different data I want to clear the previously created items and then put...
0
7204
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7091
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7342
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7464
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
5018
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4680
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3171
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3162
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1516
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.