/    Sign up×
Community /Pin to ProfileBookmark

Best way to write queries or get results

I am not sure exactly how to explain this so bare with me. I have a conditional query search and want some advice on the best way to approach this. I don’t think the way I am doing it is the best way so your help would be appreciated. Thanks again for your help.

Here is what I am attempting. I want to pull some conditional results based on the number that is pulled. Here is a basic example…

[code=php]
$query = “SELECT * FROM $tbname WHERE option1=’$option1′;
$result = mysql_query($query, $connect);
$num = mysql_num_rows($result);
$highNum = 6;

if($num > $highNum){
$query = “SELECT * FROM $tbname WHERE option1=’$option1′ AND option2=’$opiont2′”;
$result = mysql_query($query, $connect);
$num = mysql_num_rows($result);
} else if($num > $highNum) {
$query = “SELECT * FROM $tbname WHERE option1=’$option1′ AND option2=’$opiont2′ AND option3=’$option3′”;
$result = mysql_query($query, $connect);
$num = mysql_num_rows($result);
} else if($num > $highNum) {
// and so on until the search query comes below the number 6
}
[/code]

The trick for me is that I want to add more options down the road and for the true application it can result in a lot of if/else statements. Not only can this become time consuming, it’s a lot of code to go back and edit later. I don’t mind doing the work but I would also like to try and keep the code as efficient and quick as possible.

Any suggestions on how to improve this. I hope my explanation is clear and understandable. Thanks again for the help.

to post a comment
PHP

13 Comments(s)

Copy linkTweet thisAlerts:
@NightShift58Feb 10.2007 — I think that the following could get you started:[code=php]
<?php
$maxROWS = 6;
$tbname = "my_table";
$base_sql_cnt = "SELECT count(*) as cnt FROM $tbname ";
$base_sql_sel = "SELECT * FROM $tbname ";

$arrOPTION = array();
$arrOPTION[] = array("option1", $option1);
$arrOPTION[] = array("option2", $option2);
$arrOPTION[] = array("option3", $option3);
$arrOPTION[] = array("option4", $option4);
$arrOPTION[] = array("option5", $option5);
$arrOPTION[] = array("option6", $option6);

$thisSTEP = 1;
$maxSTEP = count($arrOPTION);
$continueLOOP = true;
WHILE ($thisSTEP <= $maxSTEP AND $continueLOOP) :
$sql_build = array();
FOR ($x = 0; $x < $thisSTEP; $x++) :
$sql_build[] = $arrOPTION[$x][0] . " = " . "'" . $arrOPTION[$x][1] . "'";
ENDFOR;
$sql_select = implode(" AND ", $sql_build);
// perform a "count" query
$sql_stmt = $base_sql_cnt . " WHERE " . $sql_select;
$result = mysql_query($sql_stmt) or die("SQL Error: $sql_stmt<br>" . mysql_error());
$r = mysql_fetch_array($result);
IF ($r['cnt'] > $maxROWS)
$thisSTEP++;
ELSE :
$continueLOOP = false;
ENDIF;
ENDWHILE;

// perform the "retrieval" query
$sql_stmt = $base_sql_sel . " WHERE " . $sql_select;
$result = mysql_query($sql_stmt) or die("SQL Error: $sql_stmt<br>" . mysql_error());
?>[/code]
A loop cannot go on [I]ad nauseam[/I] - it needs to be fed some limits. In this case, we use the length of the "options" array. As long as there are elements in the "options" array, the loop will cycle through until it reaches a count of $maxROWS or less.
Copy linkTweet thisAlerts:
@aussie_girlFeb 10.2007 — Or maybe or can redesign your database tables and create full indexes on the columns that your want searched and use MATCH AGAINST queries
Copy linkTweet thisAlerts:
@lincolnwayauthorFeb 10.2007 — NightShift58

- I think that might work. I will give it a try

aussie girl

- Could you elaborate on that a little more. Just curious about all my options. One thing you should know is that the data is coming from a third party source in a tab delimited file which I upload to my database. Unfortunately I don't have any control over how the data is sent to me.

Not sure if that will make a difference.

Either way, thanks for the replies, it has been helpful.
Copy linkTweet thisAlerts:
@NightShift58Feb 10.2007 — You're welcome!
Copy linkTweet thisAlerts:
@aussie_girlFeb 10.2007 — well i use one input text box where people type in keywords then I use that as part of my SQL query and MATCH it AGAINST the columns that have the fulltext index...he's part my script that I use
[code=php]
echo '<form method="POST" action="' .$_SERVER['PHP_SELF'] . '" />
Keywords:<input type="text" name="words" />
<input type="hidden" name="submitted" value="TRUE" />
<input type="submit" name="submit" value="Search!" />
</form>';

if(isset($_POST['submit']))
{
$errors = array();


if(empty($_POST['words']))
{
$errors[] = 'Please enter keywords to search';
}
else
{
$mysearch = trim($_POST['words']);
}

if(empty($errors))
{
$query = "SELECT DATE_FORMAT(reqDate,'%d-%m-%y') AS date, compLoc, compNo, problem, techRep, staff_id, itstaff_id
FROM requests
WHERE MATCH(compLoc, problem, techRep, staff_id, itstaff_id) AGAINST('$mysearch')";

$result = mysql_query($query);
//print results
[/code]
Copy linkTweet thisAlerts:
@NightShift58Feb 10.2007 — How do you control the incremental search aspects of the OP?
Copy linkTweet thisAlerts:
@aussie_girlFeb 10.2007 — you can't, which is why I suggested redesign of his table, since all his options seem to be column names the search will match those.
Copy linkTweet thisAlerts:
@lincolnwayauthorFeb 10.2007 — Thanks both of you. I will be working with that script today. I will let you know how it works. I appreciate your time and effort on this.
Copy linkTweet thisAlerts:
@lincolnwayauthorFeb 11.2007 — Thanks for your response. I probably wasn't real clear on what I am trying to do. Let me know if this makes more sense.

The user has some drop down options to choose from. Lets use a vehicle database as an example. So the user goes and chooses these options to find the a list of cars that best match there criteria. I Only want a limited number to show up depending on what they choose. Options might be... make, model, year, color, etc. The importance of the match will be in order, so the "Make" is the most important and the "color" is the least important. Lets say I want to pull no more than 6 and no less than 3.

If the search pulls all the options it might narrow the results to 1 or 2. I don't want that. I want at least three to pull up. So maybe the search stops searching after it matches the "make, model & year" but the color is left out because it found the suggested number of mathces need.

If it only searches "make" and "model" and the results pull more than six it will continue to search until it hits the suggested number of matches which is 3,4,5 or 6.

I hope that makes sense.

What would the best way to get a search to react to a minimum and maximum. This is a basic example but it hopefully illustrates my goal.

Thanks again for your help.
Copy linkTweet thisAlerts:
@NightShift58Feb 11.2007 — That's exactly what Post #2 will do for you, without the test for "minimum". The following will keep you between $minROWS and $maxROWS,[code=php]<?php
$minROWS = 3
$maxROWS = 6;
$tbname = "my_table";
$base_sql_cnt = "SELECT count(*) as cnt FROM $tbname ";
$base_sql_sel = "SELECT * FROM $tbname ";

$arrOPTION = array();
$arrOPTION[] = array("option1", $option1);
$arrOPTION[] = array("option2", $option2);
$arrOPTION[] = array("option3", $option3);
$arrOPTION[] = array("option4", $option4);
$arrOPTION[] = array("option5", $option5);
$arrOPTION[] = array("option6", $option6);

$thisSTEP = 1;
$maxSTEP = count($arrOPTION);
$continueLOOP = true;
WHILE ($thisSTEP <= $maxSTEP AND $continueLOOP) :
$sql_build = array();
FOR ($x = 0; $x < $thisSTEP; $x++) :
$sql_build[] = $arrOPTION[$x][0] . " = " . "'" . $arrOPTION[$x][1] . "'";
ENDFOR;
$sql_select = implode(" AND ", $sql_build);
// perform a "count" query
$sql_stmt = $base_sql_cnt . " WHERE " . $sql_select;
$result = mysql_query($sql_stmt) or die("SQL Error: $sql_stmt<br>" . mysql_error());
$r = mysql_fetch_array($result);
IF ($r['cnt'] > $maxROWS OR $r['cnt'] < $minROWS)
$thisSTEP++;
ELSE :
$continueLOOP = false;
ENDIF;
ENDWHILE;

// perform the "retrieval" query
$sql_stmt = $base_sql_sel . " WHERE " . $sql_select;
$result = mysql_query($sql_stmt) or die("SQL Error: $sql_stmt<br>" . mysql_error());
?>[/code]
Copy linkTweet thisAlerts:
@lincolnwayauthorFeb 11.2007 — Thanks a lot. I had to look at the script a little closer. Works perfectly for what I am trying to do. I appreciate your patience and help. Thanks a lot Nightshift.
Copy linkTweet thisAlerts:
@NightShift58Feb 11.2007 — You're welcome!
×

Success!

Help @lincolnway spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...