I want to sort autocomplete suggestions by first letter alphabetical.
Now it look like this: http://i.imgur.com/EevFyv2.png
If i type letter C i want to show tag suggestions like this:
C
C++
Active Directory
Apple Script
BlueCoat
Code:
$text = $mysqli->real_escape_string($_GET['term']);
$query = "SELECT * FROM autocomplete WHERE name LIKE '%$text%' ORDER BY name ASC";
$result = $mysqli->query($query);
$json = '[';
$first = true;
while($row = $result->fetch_assoc())
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;
I hope someone could help, thanks in advance.
You would need
SELECT *
FROM autocomplete
WHERE name LIKE '%$text%'
ORDER BY (name LIKE '$text%') DESC,
name ASC
The first ORDER BY clause is a BOOLEAN value that is 1 when name starts with $text and 0 otherwise, so when you sort by that in DESC order, values starting with $text will be moved to the front of the list (and those only containing it elsewhere will be moved to the end). The second clause then sorts both "sublists" alphabetically again.
Update. As it seems that you need suggestions that start with the entered prefix to appear first in the list, you'll need to use a user-sorting function. I've updated the code to match this.
If you want to do the sort in PHP, you need to create an array with the results, and sort it via one the PHP array sorting function. Here's your modified code that uses the usort() function:
$term = $_GET['term'];
$text = $mysqli->real_escape_string($term);
$query = "SELECT * FROM autocomplete WHERE name LIKE '%$text%' ORDER BY name ASC";
$result = $mysqli->query($query);
$results = array();
while($row = $result->fetch_assoc())
{
$results[] = $row['name'];
}
usort($results, function($item1, $item2) use($term) {
// prefixed items need to go first
$item1HasPrefix = strpos($item1, $term) === 0;
$item2HasPrefix = strpos($item2, $term) === 0;
if($item1HasPrefix && $item2HasPrefix) {
// if both items have the prefix, sort them
return strcmp($item1, $item2);
} elseif($item1HasPrefix) {
return -1;
} elseif($item2HasPrefix) {
return 1;
} else {
return strcmp($item1, $item2);
}
});
echo json_encode($results);
You can try bootstrap-typeahead JS autocomplete library in Client Side.
https://twitter.github.io/typeahead.js/examples/
Related
How do i str_split each character result output from mysqli database i have tried:
require("init.php");
$result = mysqli_query($conn, "SELECT item_name , quantity FROM books WHERE book = 1905515");
if($row = mysqli_fetch_assoc($result))
{
$da = $row["item_name"];
$qty = $row["quantity"];
}
$sql = mysqli_query($conn, "SELECT name , recharge , details , logo , price FROM promo WHERE code='$da' LIMIT 1");
if($rrow = mysqli_fetch_assoc($sql))
{
$code = $rrow["recharge"];
$see = str_split($code, 2);
echo "<br/>$see"; // not working fine, outputs 'Array'
echo "$code"; // working fine
}
all i get as result is 'arrary' thanks for your time and impact
A few directions here, I will give a few examples.
1) If you are simply wanting to echo out each row column, with a break, then all you need is this:
if($rrow = mysqli_fetch_assoc($sql))
{
echo '<br>' . $rrow['recharge'];
}
2) If you do need to split the 'recharge' column into 2-character array values, and then output those again as a solid string, you could do this:
if($rrow = mysqli_fetch_assoc($sql))
{
$codebits = str_split($rrow['recharge'],2);
echo '<br>' . implode('',$codebits);
}
3) And if you needed to put each 2-character split on its own html row, you can add that to the implode like this:
if($rrow = mysqli_fetch_assoc($sql))
{
$codebits = str_split($rrow['recharge'],2);
echo implode('<br>',$codebits);
}
4) However, how or what you are wanting to do with the code from 'recharge', is flexible at this point. Various ways we can go with it, and since its in an array, you can even wrap each array element in more html as you need:
if($rrow = mysqli_fetch_assoc($sql))
{
$codebits = str_split($rrow['recharge'],2);
foreach($codebits as $codebit) {
echo '<div class="something">'. $codebit .'<span>more html</span></div>';
}
}
Well its kind of complicated to describe what i am trying to do, let me explain completely. first of all i have selected one or more than one option from multiple selection and implode it into a column, now i want display each selections IDs name in one column.
1st implode:
$gallery_category = implode(' ',$_POST['gallery_category']);
then trying to display each unique ids name, like this
$gallery_category = $row['gallery_category'];
$output = explode(" ", $gallery_category);
$query = 'SELECT * FROM gallery_category WHERE gallery_category_name2 = "'.$output.'"';
$select_categories_name = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($select_categories_name)) {
$gallery_category_name = $row['gallery_category_name'];
echo "<td> $gallery_category_name</td>";
}
getting error like: Notice: Array to string conversion
$gallery_category = $row['gallery_category'];
$output = explode(" ", $gallery_category);//this is an array so have to give it in a loop or specify by index
foreach($output as $category)
{
$query = 'SELECT * FROM gallery_category WHERE gallery_category_name2 = "'.$category.'"';
$select_categories_name = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($select_categories_name)) {
$gallery_category_name = $row['gallery_category_name'];
echo "$gallery_category_name";
}
}
This should work, if not pls comment.
code:
<?php
include('config.php');
$return_arr = array();
$term = $_GET['term'];
$term = str_replace('.','',$term);
$sql = "SELECT * FROM submission where keyword like '".$term."%' or keyword
like '%".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";
$r = mysqli_query($link,$sql);
while($row = mysqli_fetch_assoc($r))
{
$key = explode(",", $row['keyword']);
foreach ($key as $keyword)
{
$return_arr[] = $keyword;
}
}
echo json_encode($return_arr);
?>
I have created autocomplete suggestion box and its working properly but I have a column name keyword where my data is look line apolo,alto,bmw,camaro,ducati like this where I am using expload function for listing one by one. If I search with (a) alphabet it showing a result but when I want to search with (b) alphabet its show nothing. So, How can I remove this problem ?Please help me.
Thank You
Use the IN filter to get better results for multiple keywords
SELECT keyword FROM submission WHERE keyword IN ('Apolo', 'BMW', ...);
Okay essentially what I'm trying to achieve is to combine the first query with the second one the trouble I'm having is that I'm unable to array out the results from the first query to then use in the second one. Here is my first query what this achieves is that it selects all the room subjects from my users which typically look like this, welcome to my #room hope you #enjoy once is selects one it will then strip the subject of the words and will only keep the hash-tags for example it will keep #room and #enjoy once its goes through and selects all the hash-tags from all of the room subjects it will then order them from how frequent they are used among subjects of all users.
$sql = mysql_query("SELECT subject FROM `users`");
$row = mysql_fetch_array($sql);
$freqDist = [];
foreach($results as $row)
{
$words = explode(" ", $row);
foreach($words as $w)
{
if (array_key_exists($w, $freqDist))
$freqDist[$w]++;
else
$freqDist[$w] = 1;
}
}
arsort($freqDist);
foreach($freqDist as $word => $count)
{
if (strpos($word, '#') !== FALSE)
echo "$word: $count\n";
else
echo "$word: does not contain hashtag, DROPPED\n";
}
Now what I'm trying to achieve here is that I'm trying to array out the results from the above query so then I can perform an action on each hash-tag which is grabbed from above. Below I have included the code and essentially the problem I face lies solely on this line $all = array("hashtag1", "hashtag2", "hashtag3"); as what I'm trying to achieve is instead of typing in directly the hash-tags I want to perform the action on I would want them to be grabbed via using the above query.
$all = array("hashtag1", "hashtag2", "hashtag3");
$trending = $all;
foreach($trending as $tags)
{
$sql = mysql_query("SELECT * FROM `users` WHERE `subject` LIKE '%$tags%'");
$sums = mysql_query("SELECT SUM(viewers) AS viewers FROM `users` WHERE `subject` LIKE '%$tags%'");
$num_rows = mysql_num_rows($sql);
$row = mysql_fetch_assoc($sql);
$sum = mysql_fetch_assoc($sums);
}
So again just to outline my problem I'm trying to grab the results from the first query and use them as an array with the second query. I apologise for the length of this question I just assumed it would help you better understand my question.
As per my understanding, you want to store the hashtag value in an array. if so then just update your foreach()
$hashWord = array();
foreach($freqDist as $word => $count)
{
if (strpos($word, '#') !== FALSE)
echo "$word: $count\n";
$hashWord[] = $word;
else
echo "$word: does not contain hashtag, DROPPED\n";
}
Hello everyone I have really chalenging task I have to sort an array by condition with mysql select or by another array. Imagine something like that
$arrayINeedToSort = array(5,4,7,96,1,0,55);
// Dont know if it is important cause of next step
sort($arrayINeedToSort);
$arrayToCheckDuplicData = array();
foreach($arrayINeedToSort as $aid)
{
$sql = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId = $aid ");
$num = mysql_num_rows($sql);
if($num)
{
echo $aid;
}
else
{
// skip this id cause it is not in array but i would like to push at the end of an array again sorted
if(in_array($aid,$arrayToCheckDuplicData))
{
echo $aid;
}
else
{
$arrayINeedToSort[] = $aid;
}
$arrayToCheckDuplicData[] = $aid;
}
}
Thats my idea, pushing array values to the end of acutal array with another simple array check but i am open to different/better ideas.
UPDATE //////////////////////////////////////////////
I need to see all ids so i cant skip them and I need them sorted.
TO BE MORE SPECIFIC i would liek to have input like this
1,4,96 (of values which are in database ) 0,5,7,55 (of values which are not in databse) at the end array will look like this
$outputSortedArray(1,4,96,0,5,7,55);
Could you please be more specific in what you want. On what is the input and what you want in your output.
If you need to sort the array $arrayINeedToSort then use sort function.
Give an example of the input and output array. Also the table with condition you wanted to check.
Check the following code and verify if this is what you want:
`
$arrayINeedToSort = array(5,4,7,96,1,0,55);
$in_cond = implode(",", $arrayINeedToSort);
$arrayToCheckDuplicData = array();
$result = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId IN (" . $in_cond . ") ORDER BY arrayValueId ASC");
$num = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if (in_array($row["arrayValueId"], $arrayINeedToSort)) {
echo $row["arrayValueId"];
}
else {
if (in_array($row["arrayValueId"], $arrayToCheckDuplicData)) {
echo $row["arrayValueId"];
}
$arrayToCheckDuplicData[] = $row["arrayValueId"];
}
}
`
You can use php array sorting functions: http://www.php.net/manual/en/array.sorting.php
There is also a function called array_unique, which is delete multiple values from an array.
If you want to sort the array in the MySQL query, use "ORDER BY ASC/DESC".