ignore entered text after a certain length PHP JQuery Search - php

I'm using the Tutorial to create a search engine. However I want the user to be allowed to keep typing in the search but make the search ignore anything after a certain amount of text has been entered.
I see right here
include_once ('database_connection.php');//Including our DB Connection file
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select topictitle,topicdescription from topics where topictitle like '%$keyword%' or topicdescription like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if atleast one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
echo '<p> <b>'.$row['topictitle'].'</b> '.$row['topicdescription'].'</p>' ;
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
But I don't know how I can make it so after the user has typed 7 charactors let the user keep typing but ignore anything after the 7th charactor. Any help?

Try this
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
if(strlen($keyword) > 7){
$keyword = substr($keyword,0,7);//This will give you first 7 characters if the user input is greater than seven characters in length.
}

<?php
include_once ('database_connection.php');//Including our DB Connection file
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword=$_GET['keyword'];
if(strlen($_GET['keyword'])>7)
{
$keyword= substr($_GET['keyword'],0,7);
}
$keyword = trim($keyword) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select topictitle,topicdescription from topics where topictitle like '%$keyword%' or topicdescription like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if atleast one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
echo '<p> <b>'.$row['topictitle'].'</b> '.$row['topicdescription'].'</p>' ;
}
}
else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}
else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
?>

Related

PHP Search form is testing only last row of the database

I am trying to create a search facility for a website. the website contains text posts so the database has a table post_record with field post_id, post_title, post_href and post_content.
now the working is when a user enters any search keyword in search field, that keyword is being tested against all the post titles and post contents and where it matches it should return all those rows. Following is the code for it. the issue is its returning only the last row of the databse.
<table class="s_table">
<?php
require_once'config.php';
if(isset($_POST['search_btn']))
{
$mes = " ";
$search_key =" ";
$search_key = ($_POST['search_field']);
try
{
if(empty($search_key) && $search_key != " ")
{
echo $mes = "Enter the keyword you want to search.";
}
else
{
$result = $conn->prepare("SELECT * FROM post_record WHERE post_title LIKE '%".$search_key."%' OR post_content LIKE '%".$search_key."%'");
$result->execute();
$count=$result->rowCount();
$datas = $result->fetchAll();
if(!$count)
{
echo $mes = "No Result found. Try another keyword for search.";
}
else
{
foreach ($datas as $data)
{
echo "
<tr><td><b><u><a href='".$data['post_href']."'>".$data['post_title']."</a></b></u></td></tr><br>
<tr><td class='s_cont'>".$data['post_content']."</tr></td><br><br>";
}
}
}
}
catch(PDOException $e)
{
$mes = "Something Went Wrong! try again";
header("location:index.php");
}
}
$conn = null;
?>
Everything is working fine except the thing that it is displaying only last row of the database.
Right now database has 3 posts and for testing purpose i tried a keyword that i know is common in all the post contents but its not working. only last row the database is being fetched and tested.
if(empty($search_key) && $search_key != " ") this condition is wrong
Both are different things which wont get true ever.
you are testing if its empty and then u r testing if its not empty
Both in same if condition
I usually use procedual functions but I encounter a problem like this with the mysqi_fetch_array(), so your problem might be that fetchAll() is moving the cursor to the last record. Try to remove that function or use mysql_data_seek($datas , 0) before the foreach() .

Creating a php search from Mysql database

I am building a bus reservation system using php & mysql.
In here I am trying to input the search field "route" which is fields of the mysql table.
It seems to have problem in searching and printing the results to the page. Please help me out.
<?php
$connect=mysqli_connect("localhost","root","","tsms");
$output ='';
if(isset($_POST['from'])){
$searchq = $_POST['from'];
$query = mysqli_query("SELECT * FROM bus WHERE route='$serchq' ");
$count = mysqli_num_rows($query);
if($count==0){
echo "<script>
alert('No bus services are found');
</script>";
} else {
while($row = mysqli_fetch_array($query)){
$imageData = $row['image'];
$arrival = $row['arrival_time'];
$departure = $row['departure_time'];
$type = $row['bus_type'];
$class = $row['class'];
$name = $row['bus_name'];
$facilities = $row['facilities'];
$reservation = $row['reservation_fee'];
$output = '<div>'.$arrival.''.$departure.''.$type.''.$class.''.$name.''.$facilities.''.$reservation.'</div>';
}
}
}
echo $output;
?>
Not sure where is the problem, but the sql comparison with "=" searches for a perfect match. Try to use the "like" as
SELECT * FROM bus WHERE route like '%$serchq%'
also, do escape the serchq, because you can get hacked this way.
In your search form, do you have a (dropdown) input or a simple text input?
In your sql query, you are searching for an exact match.
Should this be your issue, consider changing "route='$serchq'" to "route LIKE $serchq" for a more broad match. Also the quotes are not necessary around $serch so eliminating them might help.

Improving Ajax auto-complete to return better result

I am using ajax & php to fetch elements that matches keys(letters) entered by user with elements resembling the database.
for e.g database contain manufacturer names as:
Hydfloo, Rexflex, Easton, Vickters, EVER GUSH, Thomas Hydraulics, AVT Pumps
and say for example user has entered the letter "H" into the input box. Then I only receive Hydfloo as return and not Thomas Hydraulics along with it. Also if "p" is typed I wd expect to see "AVT Pumps". What changes do I need to make to my php in order to be able to have all the values returned that matches either the first or even the second word of the manufacturer name.
PHP code
<?php
require('../config/connection.php');
if(!$dbc) {
echo 'Could not connect to the database.';
} else {
if(isset($_POST['queryString'])) {
$queryString = mysqli_real_escape_string($dbc, $_POST['queryString']);
if(strlen($queryString) >0) {
$query = mysqli_query($dbc, "SELECT distinct name FROM prdct_subcat WHERE name LIKE '$queryString%' LIMIT 10");
echo '<ul>';
while ($result = mysqli_fetch_assoc($query)) {
echo '<li onClick="fill(\''.addslashes($result['name']).'\');">'.$result['name'].'</li>';
}
echo '</ul>';
}
}
}
?>
Use a regular expression instead of LIKE, so you can match a word boundary anywhere in the value.
Change
WHERE name LIKE '$queryString%'
to:
WHERE name REGEXP '[[:<:]]$queryString'
in the SQL.

PHP Search Query is not working

I am trying to do a search on my website but for some reason my SELECT query is swapping the keyword and name of the column name when it is executed. Below is code for my query:
if(empty($_POST)=== false){
$output = '';
$error = '';
$input = $_POST['search_input'];
$i=0;
if($input){
$keyword = explode(" ", $input);
require ('core/dbconnection.php');
//If a user is logged in check if the user is Admin or Customer.
if(isset($_SESSION['userid'])){
if($admin == 1){
//enter admin code here
}
}else{
//If user is not logged in search items table only.
$search_items = "SELECT * FROM fyp_items WHERE ";
foreach($keyword as $k){
$i++;
if($i == 1){
$search_items .= "name LIKE $k OR description LIKE $k";
}else
$search_items .= " OR name LIKE $k OR description LIKE $k";
}
$item_qry = mysql_query($search_items)or die(mysql_error());
}
}else
$error = '<p class="pageerror">Please enter your search terms.</p>';
The $search_items is concatanating the search query which is then executed by $item_query .
So I searched for "conwerse" and echo'ed out the $search_itemsvariable I got the following:
http://awesomescreenshot.com/0302ft5mc3
However, when I run the query I get this mysql_error...
http://awesomescreenshot.com/0552ft6bb4
Seems like it swaps the keyword and column name when I run the query. My database tables are of type InnoDB> I would much appreciate your help!
First of all, dont use mysql_query as all mysql_ functions are deprecated. Use mysqli or pdo.
Second, escape your keywords with mysql_escape_string();, like
$k = mysql_real_escape_string($k);
Third, your query, when you echo it, needs to look like this:
SELECT * FROM fyp_items WHERE `name` LIKE 'conwerse' OR `description` LIKE 'conwerse';
There is more, but this should get you started.

PHP Search Engine no results are returned even if the input matches data in the table

I'm trying to create a search engine for my website where users can enter keywords and the PHP script will search the 'name' and 'description' columns of my fyp_items table. So far I have managed to break down the input to an array of words and am try to execute a SELECT query on my database.
THE ISSUE is that it fails to find the items even if the keyword matches that of the data in the table. Below is my script...I hope someone can help me.
if(empty($_POST)=== false){
$output = '';
$error = '';
$input = $_POST['search_input'];
$i=0;
if($input){
$keyword = explode(" ", $input);
require ('core/dbconnection.php');
//If a user is logged in check if the user is Admin or Customer.
if(isset($_SESSION['userid'])){
if($admin == 1){
}
}else{
//If user is not logged in search items table only.
$search_items = "SELECT * FROM fyp_items WHERE ";
foreach($keyword as $k){
$k = mysql_real_escape_string($k);
$i++;
if($i == 1){
$search_items .= "name LIKE '$k' OR description LIKE '$k'";
}else
$search_items .= " OR name LIKE '$k' OR description LIKE '$k'";
}
$item_qry = mysql_query("$search_items")or die(mysql_error());
$numrows = mysql_num_rows($item_qry);
if($numrows > 0){
$output = 'found it';
}else
$error = '<p class="pageerror">Sorry, what you were looking for was not found.</p>';
}
}else
$error = '<p class="pageerror">Please enter your search terms.</p>';
I have tested the post by echoing the output and I have also echoed the $search_items variable to get this...
http://awesomescreenshot.com/05c2fwytac
Your help will be much appreciated!
You're building an incorrect query string, that'll be something like
SELECT ... WHERE name LIKE 'foo' OR description LIKE 'foo'
a LIKE comparison without wilcards is pointless. You've functionally got the equivalent of
SELECT ... WHERE name='foo' OR description='foo'
The wildcards allow substring matching in the fields:
SELECT ... WHERE name='%foo%' OR description = '%foo%'
so the word foo can appear ANYWHERE in the field and match. Right now your query will only match if foo is the ONLY thing in either field.
And these sorts of queries are highly inefficient, especially as the number of search terms climbs. You should be suing a fulltext search: https://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Categories