SQLite3::query(): Unable to prepare statement: 1, unrecognized token "" - php

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

Related

How to implement REGEXP in foreach the right way?

Hello,
How to add regexp the right way in this code in order to search for exact word in database?
$condition = '';
$name = "he is mad";
$query = explode(" ", $name);
foreach($query as $text) {
$condition .= "test LIKE '%".mysqli_real_escape_string($conn, $text)."%' OR ";
}
$condition = rtrim($condition, " OR ");
$sql_query = "SELECT * FROM test WHERE " . $condition;
$result = mysqli_query($conn, $sql_query);
if ($result->num_rows > 0) {
echo "1";
} else {
echo "0";
}
$conn->close();
I want to add this to the php code
SELECT
*
FROM
`table`
WHERE
Description regexp '(^|[[:space:]])pen([[:space:]]|$)';
It only works with me like this without foreach:
$sql_query = "SELECT * FROM test WHERE test regexp '(^|[[:space:]])$condition([[:space:]]|$)'";
You just need to remove the last " OR " from your $condition
<?php
$condition = '';
$name = "Hello world i am so sad";
$query = explode(" ", $name);
foreach($query as $text) {
$condition .= "test LIKE '%".mysqli_real_escape_string($conn, $text)."%' OR ";
}
// HERE REMOVE LAST " OR " FROM STRING
$condition = rtrim($condition, " OR ");
$sql_query = "SELECT * FROM test WHERE " . $condition;
$result = mysqli_query($conn, $sql_query);
if ($result->num_rows > 0) {
echo "1";
} else {
echo "0";
}
$conn->close();
If you have a phrase that is separated by spaces and you want to see if there is any overlap with the words, you can possibly use regular expressions:
where col regexp replace($name, ' ', '|')
Note that you should be passing $name in as a parameter.
If you care about word boundaries, you can introduce them into the regular expression. However, the exact form may depend on which regular expression library MySQL is using. The idea is:
where col regexp concat('\\b', replace($name, ' ', '\\b|\\b'), '\\b')

Adding PHP pagination to search results

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";
}
}
?>

Highligh key words in PHP search result

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.

Simple PHP pagination script not working

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";
}
}

get result on search box

i created a search toolbar on my system i am working, but it does not execute what i am searching, it always return me no results even if the keyword i searched is found on my table in database. pls help me analyze my codes, where i am miss or wrong thnks in advance.
heres my code. search.php
<form method="post" action="search.php">
<p><input type="text" name="keywords"><input type="submit" value="Search"></p>
</form>
<?php
include 'connect/func.inc.php';
if(isset($_POST['keywords'])){
$suffix = '';
//trim is for ignoring spaces on the input type text
$keywords = mysql_real_escape_string(htmlentities(trim($_POST['keywords'])));
$errors = array();
if(empty($keywords)){
$errors[]='Please enter a search keyword';
}
else if (strlen($keywords)<0) {
//strlen is for the no. of char
$errors[]='Please three or more characters';
}else if (search_results($keywords) === false){
$errors[]='Your search for '.$keywords.' returned no results';
}
if (empty($errors)) {
//search
$results = search_results($keywords);
$results_num = count($results);
$suffix = ($results_num !=1) ? 's': '';
echo '<p>Your search for<strong>'. $keywords.'</strong> returned <strong>'. $results_num .'</strong>result',$suffix, '</p>';
foreach($results as $result) {
echo '<p><strong>', $result['studId'], '</strong><br>', $result['fname'], $result['mname'], $result['lname'],'</p>';
}
//print_r(search_results($keywords));
} else {
foreach($errors as $error) {
echo $error, '</br>';
}
}
}
?>
function.inc.php
<?php
include 'db.inc.php';
function search_results($keywords) {
$returned_results = array();
$where = "";
$keywords = preg_split('/[\s]+/', $keywords);
//preg_split select evry word and ignore many spaces
$total_keywords = count($keywords);
foreach($keywords as $key=>$keyword){
$where .= "`keywords` LIKE '%$keyword%'";
if($key != ($total_keywords -1)) {
$where .= " AND ";
}
}
//echo $where;
$results = "SELECT `studId`, LEFT(`fname`, 20) as `fname`, LEFT(`lname`, 20) as `lname`, LEFT(`mname`, 20) as `mname` FROM tbl_student WHERE $where";
//echo $results;
$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0;
if($results_num === 0) {
return false;
} else {
//get info into database
while ($results_row = mysql_fetch_assoc($results)) {
$returned_results[] = array(
'studId'=> $results_row['studId'],
'fname'=> $results_row['fname'],
'mname'=> $results_row['mname'],
'lname'=> $results_row['lname']);
}
return $returned_results;
}
}
?>
my table is like this. tbl_student
studId fname mname lname
c-1111 peter jan yu
c-1112 jane trish li
By the look of it you're referencing a column that doesn't exist. Where in your database structure is a column called "keywords"? I don't see it.
From your comment under your original question it seems like you should change
$where .= "`keywords` LIKE '%$keyword%'";
to
$where .= "`studId` LIKE '%$keyword%'";

Categories