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', ...);
Related
please i need your advice. A have a search result, i want highlight search keyword in the text.
Here i perform search (searchTest.php)
$sql = "SELECT * FROM xxxx WHERE title LIKE ? OR text1 LIKE ? OR datum LIKE ? order by (datum) desc";
try {
$stmt = $connect->prepare($sql);
$stmt->execute(["%".$_POST["search"]."%", "%".$_POST["search"]."%", "%".$_POST["search"]."%"]);
$resultsNEW = $stmt->fetchAll();
if (isset($_POST["ajax"])) { echo json_encode($resultsNEW); }
Here i handle search results, that work fine.
if (isset($_POST["search"])) {
require "searchTest.php";
if (count($resultsNEW) > 0) {
foreach ($resultsNEW as $r) {
Here i try print the result with string replacement, but its not working
echo str_replace ($r, "<span style='background-color:yellow'>$_POST[search]</span>", $r["text1"]);
I'm trying to provide a search function for my PHP site. The users should be able to search rows and columns for their desired query, like "search engine". I tried this php code:
<?php
$con = #mysqli_connect("localhost", "root", "", "search");
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query = mysqli_query($con, "SELECT * FROM sites WHERE (site_title LIKE '%$search%' or site_link LIKE '%$search%' or site_keywords LIKE '%$search%')") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
print $output;
}else{
while ($row = mysqli_fetch_array($query)) {
$site_keywords = $row ['site_keywords'];
$site_tit = $row ['site_title'];
$site_link = $row ['site_link'];
$output .='<div> '.$site_tit.''.$site_keywords.''.$site_link.'</div>';
print $output;
}
}
}
?>
Everything works just fine but I'm getting duplicate results. I've read a lot of answers and here's I've done so far: I used SELECT DISTINCT * FROM .... and also SELECT DISTINCT site_id FROM .... but didn't return any result. I tries GROUP BY but they didn't remove the duplicates and returned nothing. I also applied PHP array_unique() on $row = mysqli_fetch_array($query) in where condition, but it also didn't return any result.
If I can do this by using only SQL please or I have to remove duplicates by PHP like using a function, please guide me. Thanks in advance.
Move:
print $output;
outside the loop.
Right now $output is being printed every time through the loop. If your results are A,B,C then your output will be A,A,B,A,B,C (with divs, etc.)
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";
}
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/
Ok, I have the following code:
$array = mysql_query("SELECT artist FROM directory WHERE artist LIKE 'a%'
OR artist LIKE 'b%'
OR artist LIKE 'c%'");
$array_result= mysql_fetch_array($array);
Then, when I try to echo the contents, I can only echo $array_result[0];, which outputs the first item, but if I try to echo $array_result[1]; I get an undefined offset.
Yet if I run the above query through PHPMyAdmin it returns a list of 10 items. Why is this not recognized as an array of 10 items, allowing me to echo 0-9?
Thanks for the help.
That's because the array represents a single row in the returned result set. You need to execute the mysql_fetch_array() function again to get the next record. Example:
while($data = mysql_fetch_array($array)) {
//will output all data on each loop.
var_dump($data);
}
You should be using while to get all data.
$array_result = array();
while ($row = mysql_fetch_array($array, MYSQL_NUM)) {
$array_result[] = $row;
}
echo $array_result[4];
I prefer to use this code instead:
$query = "SELECT artist FROM directory WHERE artist LIKE 'a%'
OR artist LIKE 'b%'
OR artist LIKE 'c%'";
$result = mysql_query($query) or die(mysql_error());
while(list($artist) = mysql_fetch_array($result))
{
echo $artist;
}
If you add more fields to your query just add more variables to list($artist,$field1,$field2, etc...)
I hope it helps :)