PHP search result highlight string not working - php

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"]);

Related

how to query once and display multiple times with where clause?

I want to learn how to query once and display in multiple boxes with
where clause?
like :
if status 1 ? : display in <div class="1"> elseif status 2 ?: <div class="2"> etc. etc.
I know my answer is in my question and I need to do if statements, but I dont know how to display while loop or foreach a few times with same query.
Here is my query :
$stmt = $pdo->prepare("SELECT * FROM categories");
$stmt->execute();
while($row = $stmt->fetch()){
}
I have searched on google got a few examples like this with for loop but I didnt find any examples with where claus.
$i;
$stmt = $pdo->prepare("SELECT * FROM categories");
$stmt->execute();
while($row = $stmt->fetch()){
}
for($i=0; $i<5; $i++){
}
I tried if statment without foreach loop :
if($status == 1){
foreach(){
echo "Display box 1";
}
}
if($status == 2){
foreach(){
echo "Display box 2";
}
}
Displaying only one post need while loop or foreach to display all posts with status 1
Thanks
While you could buffer multiple streams, read the entire dataset into a PHP array and search it or run multiple queries, all are unnecessary and inefficient. Just sort the query. Consider:
$stmt = $pdo->prepare("SELECT * FROM categories ORDER BY status");
$stmt->execute();
$prevstatus=-1;
print "<div style='display:none'>";
while($row = $stmt->fetch()){
if ($row['status']!=$prevstatus) {
$prevstatus=$row['status'];
print "</div><div class='$prevstatus'>";
}
print ....
}
print "</div>";
I don't know if I understand your question but:
$stmt = $pdo->prepare("SELECT * FROM articles");
$stmt->execute();
while($row = $stmt->fetch()){
echo "<div class=\"class_". $row["status"] ."\">div content</div>\n";
}
And - CSS classes can not begin with numbers or have only numbers as a name! In my example I use .class_x (where X is your value from database)

how to remove duplicate results from mysql query in php?

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.)

How to write a query for autocomplete in mysqli?

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', ...);

Search function in php using pdo [duplicate]

This question already has answers here:
PHP PDO MySQL query LIKE -> multiple keywords
(3 answers)
Closed 5 years ago.
I've been tasked with building a pretty simple search function for my groups project and I am currently stuck and can't go no further!
The idea is to search with keywords (gold, watch, leather for example), and when you hit search it's supposed to send a Select Query to the Database.
I exploded the get array and trimmed it from spaces and put % around the words, then I imploded them to one string called $searchQuery.
I have a connection to the database and when I search on a single word (just gold or watch for example), it works great and gives me the result I expect, but as soon as there is more than one word, it just says "No products found".
Below, you'll find my code. The first one is the form, the secon one is the search function pretty much. Any help would be appreciated!
<form action="index.php?action=search" method="get">
<input type="text" name="q">
<button type="submit">Sök</button>
</form>
The search function code
<?php
var_dump($_GET['q']);
$query = explode(",", $_GET['q']);
var_dump($query);
$searchQuery = array();
foreach($query as $question) {
$question = trim($question);
$question = "%".$question."%";
$searchQuery[] = $question;
}
echo "<pre>";
var_dump($searchQuery);
echo "</pre>";
$searchQuery = implode(' AND title LIKE ', $searchQuery);
echo "<pre>";
var_dump($searchQuery);
echo "</pre>";
$sql = "SELECT * FROM products WHERE title LIKE :search";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':search', $searchQuery);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
var_dump($result);
echo "</pre>";
$count = $stmt->rowCount();
?>
<ul>
<?
if($count == 0) {
echo "Inga produkter hittades";
} else {
foreach ($result as $product) {
echo "<li>";
echo $product['title'].", ".$product['price'].":-";
echo "</li>";
}
}
?>
</ul>
Your code full of errors.
First of all $question = "%".$question."%"; will generate LIKE %some% - error in sql. Should be $searchQuery[] = "'%".trim($question)."%'";
Second your WHERE title LIKE :search put whole AND LIKE '%asd%' AND LIKE '%sdf%' into single parameter and will be parsed as string. Even if this part would work, you will bump in query WHERE title LIKE AND LIKE '%asd%' AND LIKE '%sdf%' - another sql error.
I think your code should be something like
$likes = [];
foreach($query as $question) {
$likes[] = "'%".trim($question)."%'";
}
$sql = "SELECT * FROM products";
if (!empty($likes)) {
$sql .= " WHERE title LIKE "
.array_shift($likes) // remove first element from array
.implode(" OR title LIKE ", $likes); // implode rests with 'OR'
}
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

PHP Search function returning results that have numbers as a default

I am currently having an issue with my php code below for a search function on my website. Due to the array, it continues to return results (as well as the searched result) which contain numbers in the title, description or keywords.
Is there a better way I could be getting results and not returning default results that contain numbers in my database?
Live example http://www.proimagehub.com/videolist.php the search to the right.
<?php
if(isset($_POST['search'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z0-9]+/", $_POST['sitesearch'])){
$words = mysql_real_escape_string($_POST['sitesearch']);
$arraySearch = explode(" ", protect($words));
$countSearch = count($arraySearch);
$a = 0;
$query = "SELECT * FROM tutorials WHERE ";
$quote = "'";
while ($a < $countSearch)
{
$query = $query."keywords || description || title LIKE $quote%$arraySearch[$a]%$quote ";
$a++;
if ($a < $countSearch)
{
$query = $query." || ";
}
}
//-run the query against the mysql query function
$result=mysql_query($query) or die(error);
$counters = mysql_num_rows($result);
echo "<h3>Search Results for: ".$words."</h3>";
echo "<h5>Total Matching Results: ".$counters."</h5>";
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$Keywords=$row['keywords'];
$Description=$row['description'];
$Title=$row['title'];
$ID=$row['id'];
$Rank = $row["rank"];
$Type = $row["type"];
$Image = $row['img'];
$ImageNumber = $row['imgnum'];
$Video = $row['video'];
//-display the result of the array
?>
The main problem is that the query part
... WHERE keywords || description || title LIKE '...'
is not working as expected. || is a logical OR operator. It is not some kind of semantic OR operator which will automatically be combined with the LIKE operator in the way you hope.
You have to use the LIKE operator on the individual fields like:
WHERE
keywords LIKE '...' OR
description LIKE '...' OR
title LIKE '...'

Categories