dcclassics
dcclassics

Reputation: 896

jQuery Autocomplete/Typeahead from MySQL Query to PHP Array

Sorry for the long title. It's taken me an hour, but I've finally got this working. My question is if there's a much quicker, more efficient way to do what I'm doing here.

Basically, I've got an HTML text input field that uses jQuery to populate autocomplete dropdown answers (in this case, artists for a list of songs I've favorited). I previously had it working smoothly until I found that it was displaying duplications of some artists who I had favorited more than one song of. So I needed to use array_unique() to get rid of the duplicates.

Unfortunately my list was not in array form from the MySQL results, but just a string. After fiddling around for a while I got it to display in an array, but now this messed up my formatting for the jQuery list. array_walk() helped me format each item in the array, and then I converted this to a string. It just seems like a lot of work. Can I do it in less steps?

Here is my code:

<input type="text" class="span3" style="margin: 0 auto; " autocomplete="off" name="artist" data-provide="typeahead" data-items="4" data-source='[<?

$artistlist = "SELECT * FROM songs where id >= 0";
$result = $mysqli->query($artistlist);

while( $row = mysqli_fetch_assoc($result)) {

$artists[] = "\"".$row['artist']."\",";
//have to format this way for the jQuery results.

$artists = array_unique($artists);
}

function formatArtists(&$artists) {
$artists = str_replace("'", "&#39;", $artists);
//have to do this because of "O'" names.

}
array_walk($artists, "formatArtists");
foreach($artists as $artist) {
$artistSelect .= $artist;
}

$artistSelect = substr(trim($artistSelect), 0, -1);
//I have to convert the array to a string so that I can trim the final comma from the list of artists.  Otherwise the autocomplete breaks.

echo $artistSelect;
?>]'>

Thanks for the help, if you notice any other inefficiencies, I'm still learning so I would not mind correction!

Upvotes: 0

Views: 595

Answers (1)

Olvathar
Olvathar

Reputation: 551

Just a few advices:

Instead of looping across $artists you should call formatArtists when you are fetching query result

You can use a simple trick for avoiding artists repetitions using the artist's name as array key

There is a php function called implode() which will avoid you some lines.

Applying them all:

<input type="text" class="span3" style="margin: 0 auto; " autocomplete="off" name="artist" data-provide="typeahead" data-items="4" data-source='[<?

$artistlist = "SELECT * FROM songs where id >= 0";
$result = $mysqli->query($artistlist);
$artists = array();
while( $row = mysqli_fetch_assoc($result)) {
    $artist_name = '"'.formatArtists($row['artist']).'"';
    $artists[$artist_name] = $artist_name;
}
echo implode(',',$artists);//Will join every element from array using , character
?>]'>

Upvotes: 2

Related Questions