Forum Moderators: coopster

Message Too Old, No Replies

Searching a database for two fields

Need a form to search two fields

         

JSoaper

11:50 am on Feb 19, 2009 (gmt 0)

10+ Year Member



I am trying to searcha database and need to search two fields, so for example I want all Shoe Companies who are New York then I type in shoes companies in one field, NY in the next field and search. The script Im trying gives me all the companies or none of the companies. Any help would be appreciated

Script here below
=========================================================

<?php
mysql_connect (localhost, "", "");
mysql_select_db (db_name);
if ($company == "")
{$company = '%';}
if ($id == "")
{$id = '%';}
$result = mysql_query ("SELECT * FROM find WHERE company = '$company%' AND id = '$id%'
");
if ($row = mysql_fetch_array($result)) {
do {
print $row["company"];
print (" ");
print $row["id"];
print ("<p>");
} while($row = mysql_fetch_array($result));
} else {print "Sorry, no records were found!";}
?>

whoisgregg

2:20 pm on Feb 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



To debug SQL queries, it's helpful to do two things. First, move your query into a variable so you can echo it and see what's actually being sent to MySQL:

$sql = "SELECT * FROM find WHERE company = '$company%' AND id = '$id%'";
echo $sql;
$result = mysql_query ($sql);

Second, test the query in phpMyAdmin (or whatever frontend you use with MySQL) and see if you get what you expect there.

tbarbedo

3:40 pm on Feb 19, 2009 (gmt 0)

10+ Year Member



Try switching up your WHERE clause to use LIKE instead of '='....

$query = "SELECT * FROM find WHERE company LIKE '$company%' AND id LIKE '$id%'";

JSoaper

1:01 pm on Feb 20, 2009 (gmt 0)

10+ Year Member



Thank you... but still fails to be selective.. any other suggestions greatly appreciated.

whoisgregg

2:16 pm on Feb 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



JSoaper, did you echo the query and test in phpMyAdmin? Did the query look right?

If you get the same incorrect response in phpMyAdmin, then you may want to experiment there in getting the query just right.

sonjay

4:03 pm on Feb 20, 2009 (gmt 0)

10+ Year Member



What's the structure of your table? I may be missing something, but your query doesn't look like it's searching for types of companies in a particular area -- it looks like it's searching for the name of a company (company = '$company') with a particular company id (id = '$id'). I don't know what you've named your fields, of course, but if it were one of my databases it would look more like
'company_location LIKE '%$location%' AND company_type LIKE '%$type%'

Is the company field the name of the companies, or the location? Is the id field the type of company they are, or the auto_id for the company?

Have you echoed out your query to see if it makes sense? Have you run it in phpMyAdmin to see if you get what you expect?