I have the below code and i am trying to highlight the search keywords on echoing the results. I have tried what is here
and here
but didn't work.
Please where am i getting it wrong.
Below is my code
if (isset($_GET["mainSearch"]))
{
$condition = '';
// $mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
//TRYING TO HIGHLIGHT SEARCH KEYWORD HERE.
$wording = str_replace($keyword, "<span style='font-weight: bold;'>".$keyword."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
}
}
else
{
echo "No results found";
}
}
Thank you very much.
Related
I have a search code that uses pagination to display results but the pagination is not displaying or working. I want such that 7 results are displayed per page view but cant seem to get it to work.
Kindly help me point out the issue and i need to understand why the pagination isn't working even though the search query is.
Below are my codes:
if (isset($_GET["mainSearch"]))
{
$condition = '';
$mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$searchquery = $_GET['mainSearch'];
$query = explode(" ", $searchquery);
$perpageview = 7; // amount of results to display per page
if ($_GET["pageno"])
{
$page = $_GET["pageno"];
}
else
{
$page = 1;
}
$frompage = $page*$perpageview-$perpageview;
$csql = "SELECT COUNT(*) FROM questions WHERE question LIKE '%$searchquery%' OR answer LIKE '%$searchquery%'";
$cret = $db->querySingle($csql);
$pagecount = ceil($cret/$perpageview);
if ($cret == 0)
{
echo "<div class='sug'>Did you mean to ask any of this?</div>";
$sortFullMatch = "(CASE WHEN question LIKE '%".SQLite3::escapeString($searchquery)."%' OR answer LIKE '%".SQLite3::escapeString($searchquery)."%' THEN 1 ELSE 0 END) as fullmatch";
foreach ($query as $word)
{
$x++;
if ($x == 1)
{
$condition .= "question LIKE '%$word%'";
}
else
{
$condition .= "OR question LIKE '%$word%'";
}
}
$order = " ORDER BY fullmatch DESC, quiz_id DESC ";
$condition_q = "SELECT *,". $sortFullMatch ." FROM questions WHERE ".$condition.' '.$order.' LIMIT '.$frompage.','.$perpageview;
$result = $db->query($condition_q);
$concount = "SELECT COUNT(*) as count FROM questions WHERE " . $condition;
$resultCount = $db->querySingle($concount);
$pagecount = ceil($resultCount/$perpageview);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
foreach($query as $text)
{
$wording = str_replace($text, "<span style='font-weight: bold; color: #1a0dab;'>".$text."</span>", $row['answer']);
}
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
echo '<div class="modulelinks">
<div class="mfound">Founded: <span>'.$founded.'</span></div>
<div class="mowned">Ownd By: <span>'.$owner.'</span></div>
</div>
</div>';
// <div class="mavailable">Available for Export Loan: <span>'.$available.'</span></div>
}
echo '<div class="page_num">';
for ($i=1; $i <= $pageount; $i++)
{
echo ''.$i.'';
}
echo '</div>';
}
}
}
else
{
$sql = $db->prepare("SELECT * FROM questions WHERE question LIKE '%$searchquery%' or answer LIKE '%$searchquery%' LIMIT '$frompage','$perpageview'");
$bsql = $db->prepare("SELECT * FROM banks WHERE bname LIKE '%$searchquery%' or bankbrief LIKE '%$searchquery%' LIMIT 1");
$sqlcount = "SELECT COUNT(*) as count FROM questions WHERE question LIKE '%$searchquery%' OR answer LIKE '%$searchquery%'";
$retCount = $db->querySingle($sqlcount);
$pagecount = ceil($retCount/$perpageview);
$ret = $sql->execute();
$bret = $bsql->execute();
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$wording = str_replace($searchquery, "<span style='font-weight: bold; color: #1a0dab;'>".$searchquery."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
?>
//for page links
<div class="page_num">
<?php
for ($i=1; $i <= $pagecount; $i++)
{
echo ''.$i.'';
}
?>
</div>
<?php
}
?>
What could be the issue with this? Thanks.
With my current code when I enter an empty string or a string of one space in the search input field I get every item in the database as a result. How can i make it so that the search doesn't run when an empty string is entered?
<form action="search.php" method="POST">
<input type="text" name="search" placeholder="search site">
<button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
</form>
<?php
if (isset($_POST['submit-search'])){
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0){
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='articleItem'>
<h2>".$row['title']."</h2>
<p>".$row['abstract']."</p>
<a href=".$row['link']." target='_blank'>".$row['link']."</a>
</div>";
}
}
else {
echo "There are no results matching your search.";
}
}
?>
Check if isset, then trim, then confirm it still has at least one character.
if ( isset( $_POST['submit-search'] ) ) {
$search = trim( (string) $_POST['submit-search'] );
if ( isset( $search[0] ) ) { // Has at least one character?
// Run query.
}
}
If you have PHP 7+, here's a more terse syntax.
$search = trim( (string) ( $_POST['submit-search'] ?? '' ) );
if ( isset( $search[0] ) ) { // Has at least one character?
// Run query.
}
You can check string length with strlen. A trim can be additionally used to remove white spece search also.
$hasResult = false ; //default mark no result.
if (isset($_POST['submit-search']) && strlen(trim($_POST['submit-search'])) > 0) {
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
$hasResult = true ; //mark result found
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='articleItem'>
<h2>" . $row['title'] . "</h2>
<p>" . $row['abstract'] . "</p>
<a href=" . $row['link'] . " target='_blank'>" . $row['link'] . "</a>
</div>";
}
}
}
if( ! $hasResult ) { //Move to a common section
echo "There are no results matching your search.";
}
Use the below function to get the query string
<?php
$arr_with_index['title'] = $_POST['search'];
$search_qry = getLikeSearchQuery($arr_with_index)
// Add this $search_qry in your query string. This help you to searc N number of values
// For Array and Equal values
function getSearchQuery($arr_with_index) {
$search_qry = "";
if(isset($arr_with_index)){
foreach(#$arr_with_index as $index => $value) {
if(is_array($value)) {
if( implode("",$value) != '' ) {
if($index && $value) { $search_qry .= " and $index IN ('".implode("','",$value)."') "; }
}
} else {
$value = trim($value);
if($index && $value) { $search_qry .= " and "; $search_qry .= " $index = \"$value\" "; }
}
}
}
return $search_qry;
}
// For String
function getLikeSearchQuery($arr_with_index) {
$search_qry = "";
foreach($arr_with_index as $index => $value) {
$inner_flag = false;
if($index && $value) {
$field_arr = explode(",", $index);
foreach($field_arr as $field_index => $field_value) {
if(!$inner_flag) { $search_qry .= " and ( "; } else { $search_qry .= " or "; }
$value = trim($value);
$search_qry .= " $field_value like "; $search_qry .= " \"%$value%\" ";
$inner_flag = true;
}
}
if($inner_flag) { $search_qry .= " ) "; }
}
return $search_qry;
}
?>
How do i add PHP pagination to results coming from search query. I have tried here andhere but didn't seem to get how these works or should work with my code. I have written the search query before i thought of pagination cause i was using the load on scroll before. How do i make the results show paginated.
Below is my code to display searchresults.php.
if (isset($_GET["mainSearch"]))
{
$condition = '';
// $mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$wording = str_replace($text, "<span style='font-weight: bold;'>".$text."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
}
}
else
{
echo "No results found";
}
}
I was using this along side javascript to load more result on scroll
if (isset($_POST['limit']) && isset($_POST['start'])) {
$start = $_POST["start"];
$limit = $_POST["limit"];
$query =<<<EOF
SELECT * FROM questions ORDER BY quiz_id DESC LIMIT '$start', '$limit';
EOF;
// echo $query;
$result = $db->query($query);
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
echo '<div class="quesbox_2">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$row["answer"].'</div>
<div class="quesdatetime"><img src="images/questime.png" alt="export question">'.$row["date"].'</div>
</div>';
}
}
How do i add pagination to my searchresults.php?
Thanks.
try this code without using jquery
<?php
if (isset($_GET["mainSearch"]))
{
$condition = '';
// $mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
$perpageview=10;
if($_GET["pageno"]){
$page=$_GET["pageno"];
}else{
$page=1;
}
$frompage = $page*$perpageview-$perpageview;
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order.' LIMIT '.$frompage.','.$perpageview;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
$pagecount = ceil($resultCount/$perpageview);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$wording = str_replace($text, "<span style='font-weight: bold;'>".$text."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
for ($i=1; $i <= $pagecount; $i++) {
echo ''.$i.'';
}
}
}
else
{
echo "No results found";
}
}
?>
I am trying to create a PHP search query that searches by each word from the database. But i get this error when search query is submitted.
Warning: SQLite3::query(): Unable to prepare statement: 1, unrecognized token: "'%export%" in C:\xampp\htdocs\xport\searchresult.php on line 107
Below is my code.
For the search page
if (isset($_POST['mainSearch']))
{
if (!empty($_POST['mainSearch']))
{
$searchquery = $_POST['mainSearch'];
$query = str_replace(" ", "+", $_POST['mainSearch']);
header("Location: searchresult.php?mainSearch=" . $query);
}
}
Page to display search result.
if (isset($_GET["mainSearch"]))
{
$condition = '';
$query = explode(" ", $_GET['mainSearch']);
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%'";
}
$condition = substr($condition, 0, -4);
$sql_query = "SELECT * FROM questions WHERE " . $condition;
$result = $db->query($sql_query);
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
echo '<div class="quesbox_2">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$row["answer"].'</div>
</div>';
}
}
else
{
}
}
What is the reason for this error. I think its because the string is not properly escaped, if this is the reason how do i mysqli_real_escape_string() in SQLite3 (this is the database i am using). If not, Please how do i fix this.
Change the number of substring to -3.
So change
$condition = substr($condition, 0, -4);
to the new
$condition = substr($condition, 0, -3);
This should do the trick.
Try it this way if you are trying to search by each word
<?php
if (isset($_GET["mainSearch"]))
{
$condition = '';
$query = explode(" ", $_GET["mainSearch"]);
foreach ($query as $text)
{
//change condition query
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$sql_query = "SELECT * FROM questions WHERE " . $condition;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition;
$result = $db->query($sql_query);
//count query result to display something else if no records where found.
$resultCount = $db->querySingle($sql_query_count);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$row["answer"].'</div>
</div>';
}
}
}
else
{
echo "No results found";
}
}
?>
Seems you need an OR condition in your WHERE clause that will fetch all results matching any of the words. Just add OR at the end of your query part and you should be fine.
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
// Will chop 4 characters ' OR ' from end of the string
$condition = substr($condition, 0, -4);
To make it little clean, you can escapeString once when retrieved from the parameter to avoid escaping it again and again in the loop.
$mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$query = explode(" ", $mainSearch);
foreach ($query as $text)
{
$condition .= "question LIKE '%$text%' OR answer LIKE '%$text%' OR ";
}
// Will chop 4 characters ' OR ' from end of the string
$condition = substr($condition, 0, -4);
I have a php search script that search and echos out result from database. The issue is that i am trying to paginate the search results but when i click on a different page, it shows the same result. That is the search results are not shared across the pages. Please how do i fix?
Below is my code
if (isset($_GET["mainSearch"]))
{
$condition = '';
$mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
$perpageview = 10;
$page = $_GET["pageno"];
$frompage = $page*$perpageview+1-$perpageview;
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
$pagecount = ceil($resultCount/$perpageview);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$wording = str_replace($text, "<span style='font-weight: bold;'>".$text."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
for ($i=1; $i <= $pagecount; $i++)
{
echo ''.$i.'';
}
}
}
else
{
echo "No results found";
}
}
Thanks very much.
I have mentioned in your previous request check
if (isset($_GET["mainSearch"]))
{
$condition = '';
// $mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$keyword = $_GET['mainSearch'];
$query = explode(" ", $keyword);
$perpageview=10;
if($_GET["pageno"]){
$page=$_GET["pageno"];
}else{
$page=1;
}
$frompage = $page*$perpageview-$perpageview;
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = " ORDER BY quiz_id DESC ";
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order.' LIMIT '.$frompage.','.$perpageview;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
$pagecount = ceil($resultCount/$perpageview);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$wording = str_replace($text, "<span style='font-weight: bold;'>".$text."</span>", $row['answer']);
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$wording.'</div>
</div>';
}
for ($i=1; $i <= $pagecount; $i++) {
echo ''.$i.'';
}
}
}
else
{
echo "No results found";
}
}