Fulltext Search engine, multiple columns, boolean mode - php

I am making a search engine for an android app that does fulltext search and match against multiple columns against '+word1 +word2' in boolean mode.
However, I can't get any search result.
E.g. search field type- "open sea"
then, Sql will search Match...Against ('+open +sea' IN BOOLEAN MODE)
and display list of selectable results, on which each result clicked, will provide details of the particular result on a new page.
Sorry, I am a newbie in android app development.
Here is my php code for search.php
<?php
# $db = new mysqli('localhost','username','password','db');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database.
Please try again later.';
exit;
}
if(!empty($_POST)){
$term = $_POST['query'];
$words = explode(" ", trim($term));
$termArray = array();
foreach($words as $word){
if(!empty($word)){
$termArray[] = "+$word";
}
}
$searchquery = implode(" ", $termArray);
if (!$term) {
echo 'You have not entered any search details. Please go back and try again.';
exit;
}
//initial query
$query = "SELECT *
FROM servicetable
WHERE MATCH(title,cat,brand,company)
AGAINST ('".$searchquery."' IN BOOLEAN MODE)
ORDER BY title ASC";
$result = $db->$query;
$num_results = $result->num_rows;
//show user what user searched.
echo $searchquery;
echo "<p>Results found: ".$num_results."</p>";
//counts results.
if ($num_results == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>".($i+1).". Outlet Name: ";
echo stripslashes($row['title']);
echo "</strong><br />Category: ";
echo stripslashes($row['cat']);
echo "<br />Opening Hours: ";
echo stripslashes($row['ophours']);
echo "<br />Brand: ";
echo stripslashes($row['brand']);
echo "</strong><br />Company: ";
echo stripslashes($row['company']);
echo "</p>";
}
$result->free();
$db->close();
} else {
?>
<h1>Search</h1>
<form name="form1" action="search.php" method="post">
Enter Search:<br />
<input type="text" name="query" id="query" placeholder="Search a service"/>
<br/>
<input type="submit" value="Search Now" name="completedsearch" />
</form>
<?php
}
?>

Hi I have found my error:
this line correction-->
$result = $db->query($query);

Related

Blank / Empty Search Form field

I have set up a search form for my database. When I search and results are found a message is echoed below the search form. For instance, 10 records found, 0 records found.
How can I get that message to disappear if the search form field is blank/empty. Currently it displays 15 records found for a blank/empty search field. Which is all the database records.
Thanks for any help.
Form:
<form action="" method="post">
<input type="text" name="search_box" value="<?php if (isset($_POST['search_box'])) echo $_POST['search_box']; ?>" placeholder="Search here ..."/>
<input value="Search" name="search" type="submit" /><br>
</form>
PHP:
<?php
$count = mysqli_num_rows($result);
if($count > 0){
echo $count . " Records Found";
}if($count == 0){
echo "0 Records Found";
}if($count == ""){
echo "";
}
?>
Query:
//Retrieve the practice posts from the database table
$query = "SELECT * FROM practice";
//check if search... button clicked, if so query fields
if(isset($_POST['search'])){
$search_term = trim($_POST['search_box']);
$query .= " WHERE title = '{$search_term}'";
$query .= " or subject LIKE '%{$search_term}%'";}
<?php
//Retrieve the practice posts from the database table
$query = "SELECT * FROM practice";
//check if search... button clicked, if so query fields
if(isset($_POST['search'])){
$search_term = trim($_POST['search_box']);
$query .= " WHERE title = '{$search_term}'";
$query .= " or subject LIKE '%{$search_term}%'";
//execute your query
$result = $dbconnect->query($query);
$count = mysqli_num_rows($result);
if($count > 0){
echo $count . " Records Found";
}
if($count == 0){
echo "0 Records Found";
}
}
else {
// it is mean your search box value($_POST['search']) is empty, so it will echo null value
echo $_POST['search'];
}
?>
please try, hope will save your day :D
Please replace PHP code with these one :-
<?php
if(isset($_REQUEST['search_box'])){
$count = mysqli_num_rows($result);
} else {
$count = '';
}
if($count > 0){
echo $count . " Records Found";
}if($count == 0){
echo "0 Records Found";
}if($count == ""){
echo "";
}
?>
Just put your code in the post method
if ((isset($_POST['search_box'])) && ($_POST['search_box']!=""))
{
$count = mysqli_num_rows($result);
if($count > 0){
echo $count . " Records Found";
}if($count == 0){
echo "0 Records Found";
}if($count == ""){
echo "";
}
}

Search in a table using full or partial

I have a little problem where i try to search for a product and the user can choose to click on a full search or a partial search. Problem is when the user click on full search and type in something, the whole table is printing out and the word of the product is not (i want instead printing out the product and not the whole table) And with partial search, its just print outs it dont find a match. Below here is my code so far:
// DB configuration //
if (!isset($_POST["searchtype"])) {
echo "<form method='POST'>";
echo "Search for product:<br>";
# using html5 input type search
echo "<input type='text' name='searchtext' size='15' placeholder='search' results='5' autosave='saved-searches'>";
echo "<br><br>";
echo "Full search";
echo"<input type='radio' value='FULL' checked name='searchtype'><br>";
echo "Partial search ";
echo "<input type='radio' name='searchtype' value='PARTIAL'>";
echo "<br><br>";
echo "<input type='submit' value='Search' name='submit'>";
echo "</form>";
}
else {
$searchtext = $_POST["searchtext"]; # Retrieve from the form
$searchtype = $_POST["searchtype"]; # Retrieve from the form
$searchtext_san = sanitize_form_text($searchtext); # Prevents SQL injections!
try{
if($DBH == null)
$DBH = new PDO($dsn, $dbuser, $dbpass);
$sql = "select name, price, details from products where name='$searchtext_san'";
if ($searchtype == "FULL"){
$sql .= " = :searchtext_san";
$STH = $DBH->prepare($sql);
$STH->execute(array(':searchtext_san' => $searchtext_san));
}
if ($searchtype == "PARTIAL"){
$sql .= " LIKE ':searchtext_san'";
$STH = $DBH->prepare($sql);
$STH->execute(array(':searchtext_san' => '%'.$searchtext_san.'%'));
}
$STH->setFetchMode(PDO::FETCH_ASSOC);
$total = $STH->rowCount();
if ($total == 0){
echo "Sorry, no matches found!";
}
if ($total > 0){
while ($row = $STH->fetch()){
echo "{$row["name"]} {$row["price"]} {$row["details"]}<br>";
}
}
$DBH = null;
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
}
function sanitize_form_text($t)
{
$t = strip_tags($t);
$t = ereg_replace("[^A-Za-z0-9#._-]", "", $t);
return $t;
}
?>
try this for fulltext search
SELECT * FROM articles WHERE MATCH (title,body)
AGAINST ('+MySQL -YourSQL' IN BOOLEAN MODE);
Full text Search description
for partial search you can us like
SELECT name FROM products WHERE name RLIKE '[yourtext]'

Php/MySQL if statement that returns information based on value selected

[page1.php]
<form action="result.php" method="POST" style='color:white;font-family: __custom;'>
<input type="text" placeholder="Search.." name="search" /><br><br>
<center>
<select name="example">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<br><br>
</center>
<input type="submit" value="GO!" id="sub"/>
</form><br><br><br>
[result.php]
<?php
$searchq = $_POST['search'] // search textbox;
//Connect to mySQL and retrieve all contacts
$conErr = "Error connecting to server or database";
$con = mysqli_connect("host", "user", "password", "database");
// Check connection
if (mysqli_connect_errno()) {
echo $connErr;
}
if ($_POST['example'] == 'C') {
echo "You chose inCludes";
$result = mysqli_query($con, "SELECT * FROM people WHERE name LIKE '%$searchq%' ORDER BY name ASC");
while ($row = mysqli_fetch_array($result)) {
echo "<hr>";
echo "All information regarding Select Statement";
echo "<br>";
}
} else if ($_POST['example'] == 'A') {
echo "You chose EndsWith";
$result = mysqli_query($con, "SELECT * FROM people WHERE name LIKE '$searchq%' ORDER BY name ASC");
while ($row = mysqli_fetch_array($result)) {
echo "<hr>";
echo "All information based on Select Statement";
echo "<br>";
}
} else {
echo "Blah";
}
mysqli_close($con);
?>
</div>
What i'm trying to do is on page1.php the user searches for a keyword the chooses either A, B, or C from a dropdown. Based on the A, B, C the user goes to result.php and then the information is given based on the query.
The code above does not seem to be working [I do not get any results at all] [blank]. Please help.
If you want to search for something that ends with a string, you have to put the % wildcard at the beginning:
} else if ($_POST['example'] == 'A') {
echo "You chose EndsWith";
$result = mysqli_query($con, "SELECT * FROM people WHERE name LIKE '%$searchq' ORDER BY name ASC");
while ($row = mysqli_fetch_array($result)) {
echo "<hr>";
echo "All information based on Select Statement";
echo "<br>";
}
}
You missed the % wildcard after LIKE clause
else if ($_POST['example'] == 'A') {
echo "You chose EndsWith";
$result = mysqli_query($con, "SELECT * FROM people WHERE name LIKE '%$searchq%' ORDER BY name ASC");
while ($row = mysqli_fetch_array($result)) {
echo "<hr>";
echo "All information based on Select Statement";
echo "<br>";
}
}

Basic search engine not working

Hello i managed to make a simple search engine its basic so i started working on that..
But i get Access Forbidden and dont know why can someone help me?
with a form i give the $find the word i search and it should search for it..
thx for your time!`
<?php
if ($searching =="yes")
{
echo "Results";
if ($find == "")
{
echo "You forgot to enter a search term";
exit;
}
mysql_connect("localhost","Anton","zouzou13") or die(mysql_error()); mysql_select_db("Ptyxiakh") or die(mysql_error());
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
$data =mysql_query("SELECT * FROM documents WHERE keywords LIKE'%$find%'");
while($result = mysql_fetch_array( $data ))
{
echo $result['document_name'];
echo " ";
echo $result['first_paragraph'];
echo "<br>";
}
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>"; }
echo "<b>Searched For:</b> " .$find; } ?>
ok i made it simpler to see if it works like this:
<?php
error_reporting(E_ALL);
mysql_connect("localhost","Anton","zouzou13") or die(mysql_error());
mysql_select_db("Ptyxiakh") or die(mysql_error());
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM documents WHERE keywords LIKE 'helmets'");
while($result = mysql_fetch_array( $data ))
{
echo $result['document_name'];
echo " ";
echo $result['first_paragraph'];
echo "<br>";
}
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
?>
But i get the "Sorry, but we can not find an entry to match your query<br><br>"; so i cant connect to database?its just wont work :(
With PDO it should be like this??:
<?php
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
$pdo = new PDO('mysql:host=localhost;dbname=ptyxiakh', 'Anton', 'zouzou13');
// Otherwise we connect to our Database
//mysql_connect("localhost","Anton","zouzou13") or die(mysql_error());
//mysql_select_db("Ptyxiakh") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
//$data = mysql_query("SELECT * FROM documents WHERE keywords LIKE'%$find%'");
$data= $pdo->query("SELECT * FROM documents WHERE keywords LIKE'%$find%'");
//And we display the results
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
echo htmlentities($row['document_name']);
echo " ";
echo htmlentities($row['first_paragraph']);
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
i made it work its pretty basic and i guess it has deprecated thingys but il upload for ppl that search for things...
just make a simple form and then make a php file
<?php
error_reporting(E_ALL);
//This is only displayed if they have submitted the form
echo "<h2>Results</h2><p>";
$find =$_POST["find"];
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("localhost","Anton","zouzou13") or die(mysql_error());
mysql_select_db("Ptyxiakh") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM documents WHERE keywords LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo '<p> <strong>',$result['document_name'], '</strong> <br> ', $result['first_paragraph'],'... <br> </p>';
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
?>
This worked for me :) thx!

How to stop search field returning all results when submitting empty search field?

If i click on my search field and submit it without entering any text all the data in my database is returned. How is this stopped so nothing happens?
Check out the site:
weezy.co.uk/newresults.php
Thanks!
James
<?php
$conn = mysql_connect("cust-mysql-123-02", "uwee_641290_0001", "La0%-Mr4");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("weezycouk_641290_db1")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '%".$search."%' AND lastname LIKE '%".$searchterm."%'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br>';
echo '<br>';
echo '<div class="data1">';
echo $row["name"];
echo '</div>';
echo '<br>';
echo '<div class="data2">';
echo $row["lastname"];
echo '</div>';
echo '<br>';
echo '<div class="data3">';
echo $row["email"];
echo '</div>';
}
mysql_free_result($result);
?>
you should check if it's empty before making a query:
if(empty($_POST['searchterm'])){
//don't search and show an error message
}else{
//proceed as normal, do the query
}
otherwise you might end up making a query like:
WHERE name LIKE('%%')
which is really expensive and returns all your database rows
Best way to do this (imo) is to have a simple javascript checking if the input is blank or not.
It is always wise to do some front end using javascript/Jquery. form validation where you are prompting users to input something.
Once you are done you may also check on the back end using the following:
if(isset($_POST['searchterm'])){
// search for the results.
}else{
// do nothing or show proper message
}
I think the best way would be to disable the submit button on the client side whenever your search box is empty.
You could do something like:
$(document).ready(function()
{
$('#searchBox').keyup(function()
{
if($(this).val() == '')
{
$('#searchButton').attr('disabled', true);
}
else
{
$('#searchButton').removeAttr('disabled');
}
});
});
where your html is like:
<input type='text' id="searchBox" />
<input type='button' id='searchButton' value='search' disabled/>
Make sure to validate on the server side as Nicola has indicated.
I was facing some problems in the above code. So the following improved version of the above code works just fine:
<form action="searchengine.php" method="POST">
<input type="text" id = "searchbox" name="searchterm" placeholder="Search here">
<input type="submit" id = "searchbutton" value="Search" style="display:none;">
</center>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#searchbox').keyup(function()
{
if($(this).val() == '')
{
$('#searchbutton').hide();
}
else
{
$('#searchbutton').show();
}
});
});
</script>

Categories