get result on search box - php

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%'";

Related

How to prevent a database search from running on an empty string?

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

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

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

Displaying MySQL results in two columns (editing existing code)

I have been asked to revise an existing site, it's still using PHP5.3 and an old version of PHPmyDirectory, and the code is a little messy.
I'm trying to revise it to just display the list of cities in two columns. I'm trying to do it as a table, as it seemed easiest, but I could also just pull the results into to side by side divs, as there are never more than 26 cities listed (so first half or first 13 in div one, the rest in div two).
Here's the existing original code (I know its not mysqli, but we'll be redoing this site shortly so there's no sense trying to redo a million pages of code right now):
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
return $output;
}
This is what is looks like currently: Current Site
Here's what I've tried to do:
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$result_array = array();
while ($service = fetch_array($result)) {
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2) {
break;
}
else {
while ($service2 = fetch_array($result2)) {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
echo "<table>";
for ($j=0; $j<$i; $j=$j+2) {
echo "<tr>";
echo "<td>".$title_array[$j]."</td><td>".$title_array[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<p><b>".$title." will travel for an additional fee!</b></p>";
}
else {
$output .="";
}
}
return $output;
}
And here's what I'm getting: DEV site
I'm very much a PHP newbie, and my understanding is pretty spotty, but I've tried a bunch of different solutions I've found here, and can't get them to work. I'm sure I'm missing something obvious.
Thanks for any pointers!
if I got it correct you should change your
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
with
else {
$output = "<table>";
$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "";
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<tr><td>'."{$service2['title']}".'</td>';
$even_odd=false;
} else {
$output .= '<td>'."{$service2['title']}".'</td></tr>';
$even_odd=true;
}
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
if (!$even_odd)$output .="<td></td></tr>";
$output .="</table>";
}
}
Try this, I couldn't test it of course, since I've got no access to the data being loaded.
echo "<table>";
$result_array = array();
while ($service = fetch_array($result))
{
//this will loop multiple times. 7 times for Tony S. in the example.
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2)
{
break;
}
else
{
while ($service2 = fetch_array($result2))
{
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
}
}
for ($j=0; $j < count($result_array); $j++)
{
if ($j % 2 == 0)
{
echo "<tr>";
}
echo "<td>".$result_array[$j][0]." (".$result_array[$j][1].")</td>";
if ($j % 2 == 0)
{
echo "</tr>";
}
if ($j % 2 == 1 && $j == count($result_array)-1)
{
echo "<td></td></tr>";
}
}
echo "</table>";
Paste and replace between this lines:
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
.... PASTE IN HERE ....
}
Building on Kim's code, I was able to get it working with some revisions. I also scrapped the table for divs, since it seems less messy to me and it seemed like the table styling was interfering somehow.
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
} else {
$output = "<div>";
//$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<div style="float:left;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=false;
} else {
$output .= '<div style="float:right;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=true;
}
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<div style='clear:both;width:90%;float:none;'><p><b>".$title." will travel for an additional fee!</b></p></div>";
} else {
}
}
return $output;
}
Thanks so much Kim and Mouser!

PHP : Multiple Textform Search

So , i got a form to search for jobseeker through the database . The form contain name , identity card , job position , academic certificate , age etc . The problem that i'm facing is when i'm searching for jobseeker based only on one text form for example , job position , the result is shown . But , if i want to search for jobseeker based on job position and academic level , the result is shown based on job position only . Is there anything wrong with my code ? need help here .. sorry for my bad english though ..
for job position :
$jawatan_arr = explode(',', $_POST['txt_jawatan']);
$jum_jawatan = count($jawatan_arr);
//echo "jum_didik = ".$jum_didik;
if($jum_jawatan > 0){
$d = 0;
foreach ($jawatan_arr as $value){
$d++;
//echo "; value::: ".$value." :::";
if($d == 1){
if($value != ''){
if($str == ''){
$str = " WHERE ";
}
else{
$str .= " AND ";
}
$str_jawatan .= " (LOWER(jawatan) LIKE '%".strtolower(rtrim(ltrim($value)))."%' ";
}
}
else{
if($value != ''){
$str_jawatan .= " OR LOWER(jawatan) LIKE '%".strtolower(rtrim(ltrim($value)))."%' ";
}
}
}
if($str_jawatan != ''){
$str_jawatan .= ") ";
$sql = "SELECT no_kp FROM jobseeker_pengalaman ".$str_jawatan;
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)){
if($row['no_kp'] != ''){
if(!in_array($row['no_kp'], $senarai_kp)){
array_push($senarai_kp, $row['no_kp']);
}
}
}
}
}
for academic level(checkbox , not a textform) :
$didik_arr = explode(',', $_POST['txt_taraf_pendidikan']);
$jum_didik = count($didik_arr) - 1;
//echo "jum_didik = ".$jum_didik;
if($jum_didik > 0){
$d = 0;
foreach ($didik_arr as $value){
$d++;
//echo "; value::: ".$value." :::";
if($d == 1){
if($str == ''){
$str = " WHERE ";
}
else{
$str .= " AND ";
}
$temp_didik .= $value;
}
else{
if($value != ''){
$temp_didik .= ",".$value;
}
}
}
//$str_didik .= " id_taraf_pendidikan IN (".$temp_didik.")";
$sql = "SELECT no_kp FROM jobseeker_pendidikan WHERE id_taraf_pendidikan IN (".$temp_didik.")";
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)){
if($row['no_kp'] != ''){
if(!in_array($row['no_kp'], $senarai_kp)){
array_push($senarai_kp, $row['no_kp']);
}
}
}
}
Do i need to join the my table ? because the job position is based on recent job experience , and academic is based on their study . Both of them are from different table
May be you can try IN statement? Something like this:
$sql = "SELECT no_kp FROM jobseeker_pengalaman ".$str_jawatan." IN
(
SELECT no_kp FROM jobseeker_pendidikan WHERE id_taraf_pendidikan IN (".$temp_didik.")
)";
So you will search by job positions within that jobseekers that already passed through your academic based search. I hope this approach will help.

Value of variable is not stored correctly while transfering the value from HTML form to PHP file

Thanks Ben, but now the other issue that I am facing is that result is not being displayed first time when I add the pagination to the code. See the second half of the code below. Please help
if(isset($_GET['k'])){ $k1 = $_GET['k']; } else { $k1 = ''; }
echo $k1;
$term = explode(" ", $k1);
$query = "SELECT * FROM database ";
foreach ($term as $each)
{
echo $each;
$i++;
if($i==1)
{
$query .= "WHERE keywords LIKE '%$each%' ";
}
else {
$query .= "OR WHERE keywords LIKE '%$each%' ";
}
}
$per_pages=3;
$page_query = mysql_query("SELECT COUNT('title') FROM kcpdatabase");
$pages = ceil(mysql_result($page_query, 0)/$per_pages) or die
($page_query."<br/><br/>".mysql_error());
$page = (isset($_GET['page'])) ? (int)
($_GET['page']) : 1;
$start = ($page - 1) * $per_pages;
$query .= "LIMIT $start, $per_pages";
$ourquery1 = mysql_query ($query);
if(!$ourquery1)
echo "No query found";
$row1 = mysql_num_rows ($ourquery1);
if($pages >= 1 && $page <= $pages){
for($x = 1; $x <= $pages; $x++)
{
echo ''.$x.' ';
}
if ($row1 > 0)
{
while($result = mysql_fetch_assoc($ourquery1))
{
echo "<tr>";
echo "<td>";
$title = $result['title'];
$link = $result['link'];
$region = $result['region'];
$sector = $result['sector'];
$theme = $result['theme'];
echo "<td> <a href=$link><h3>$title<h3></a>";
echo "<h4>Sector: $sector <br>Theme: $theme <br> Region: $region
</td> </tr>";
}
}
}
echo "</tbody>";
Below is a portion of my code where I am trying to search a word/ phrase entered in the text box. When I catch the value from the form in a php file using "$k1 = isset($_GET['k']);" the value which get's stored in variable "$each" is "1" and NOT the word or phrase entered by the user. This messess up the query which is performing the search function. Please help me to locate the error.
Please note that 'k' is the name of text box as defined in the form code below.
<form name="keywordquery" method="get" action="page2.php">
<fieldset class="fieldsetclass"><legend class="legendclass">Search by Keywords</legend>
<div id="searchbox">
<input type="text" name="k" value="<?php if(isset($_GET['k'])){echo htmlentities($_GET
['k']);} ?>" style="border: 1px, thin; width:92%; "/>
<input type="image" style="margin-bottom: 0; margin-top: 2px;" src="search.png"
value="submit" />
</div>
</fieldset>
</form>
</div>
<table cellpadding="0" cellspacing="0" border="1">
<tbody>
<?php
$connection = mysql_connect('', '', '');
if(!$connection)
echo "No database connected";
$dbase = mysql_select_db("", $connection);
if(!$dbase)
echo "No datatable connected";
$k1 = isset($_GET['k']);
echo $k1;
$term = explode(" ", $k1);
$query = "SELECT * FROM datatable ";
foreach ($term as $each)
{
echo $each;
$i++;
if($i==1)
{
$query .= "WHERE keywords LIKE '%$each%' ";
}
else {
$query .= "OR WHERE keywords LIKE '%$each%' ";
}
}
$k1 = isset($_GET['k']);
It's setting $k1 as 1 as it's ckecking to see if it's been set - in this case it has been and isset() is returning true, or 1.
what you want is:
if(isset($_GET['k'])){ $k1 = $_GET['k']; } else { $k1 = ''; }
or similar.
Thats because isset() is a bool function, check following link http://php.net/manual/en/function.isset.php
just do this
if(isset($_GET['k']))
$k1 = $_GET['k'];

Categories