Jump to content

database search query optimization


Jason0391

Recommended Posts

Can someone please double check my search query to make sure it is the minimum and most efficient coding. My goal is an exact match search of field1 from my database table and list field1, field2, field3, field4 and field5 if the part number is in the database or no results if it is not. The query works as is but I have a feeling it could be done more efficiently or professionally and minimum work for my poor little server. Thanks in advance.

<?php
//connect to the database
include("./databaseconnect.php");
//get query
$q=$_GET['q'];
//convert query to uppercase & remove all spaces and special charactars
$q=strtoupper(preg_replace("/[^A-Za-z0-9]/","",$q));
//if blank query
if ($q == "")
{
echo "You did not enter a search term";
} else {
//exact match only query	
$query  = "SELECT * FROM ".$dbtable." WHERE field1 like \"$q\"";
$result = mysql_query($query);
//if query returns no results
if(mysql_num_rows($result)==0)
{  
echo "<span class=\"noresults\">There were no results for your search</span>";
//display database results
} else {
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<span class=\'results\'>SEARCH RESULTS</span><br />
<span class=\'list\'>Part Number: ".$row['field1']."<br />
Manufacturer: ".$row['field2']."<br />
Cost per unit: ".$row['field3']."<br />
Warehouse Location: ".$row['field4']."<br />
Quantity Available: ".$row['field5']."<br />
Notes: ".$row['field6']."<br />
</span>";
}
}
}
?>

Link to comment
Share on other sites

Your query is pretty straight forward, the only thing I would recommend would be to use an exact match search ( = instead of LIKE).

 

Obviously, the entered keyword has to be an exact match.

 

for the most part, databases are built specifically to handle requests like this.

Link to comment
Share on other sites

ok, I thought everytime it ran $results like in

if(mysql_num_rows($result)==0)

and

while($row = mysql_fetch_array($result, MYSQL_ASSOC))

it was running the query

$query  = "SELECT * FROM ".$dbtable." WHERE field1 like \"$q\"";
$result = mysql_query($query);

. sorry for the confusion... I will get it oneday

Link to comment
Share on other sites

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.