Jump to content

showing only unique entries in AutoSuggest


slaterino

Recommended Posts

Hi,

I am using an AutoSuggest box that runs from a MySQL database. However, I have one problem which is that my database has multiple entries of certain words so for example, if someone typed in 'd' they would get a list of the word 'doctors' ten times. How can I amend my code so that it only lists unique entries? Below is the code for the backend:

 

<?php
$db = new mysqli('79.170.40.175', 'web175-hmc' ,'hMc21cCa', 'web175-hmc');
if(!$db) {
	echo 'ERROR: Could not connect to the database.';
} else {
	if(isset($_POST['queryString'])) {
		$queryString = $db->real_escape_string($_POST['queryString']);

		if(strlen($queryString) >0) {

			$query = $db->query("SELECT OrgType FROM Contacts WHERE OrgType LIKE '$queryString%' LIMIT 10");
			if($query) {

				while ($result = $query ->fetch_object()) {

         			echo '<li onClick="fill(\''.$result->OrgType.'\');">'.$result->OrgType.'</li>';
         		}
			} else {
				echo 'ERROR: There was a problem with the query.';
			}
		} else {

		} 
	} else {
		echo 'There should be no direct access to this script!';
	}
}
?>

 

Thanks

Russ

Problem aside, this is a slow way of doing it. W3S has a tutorial on AJAX that does this well.

 

As for this, why not change your while loop to...

 

$array = array();
while ($result = $query ->fetch_object()) {
if(!in_array($result->OrgType, $array)) {
echo '<li onClick="fill(\''.$result->OrgType.'\');">'.$result->OrgType.'</li>';
$array[] = $result->OrgType;
}
}

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.