Searching multiple terms with php - php

I'm trying to get my search form to search for multiple terms.For example "Black dog".In my $keywords they are separated with commas (Black, dog).I know that i can just enter (Black dog, ) in my $keywords but I want them to be separated with commas.If I put single term (dog) it returns result for only that term.If I put 2 (Black dog) it returns 0 results.
<form class="form-inline pull-xs-right" action="search.php" method="POST" >
<input class="form-control" type="text" name="search" placeholder="Search">
<button class="btn btn-success-outline" name="searchh" type="submit" value=">>" >Search</button>
</form>
<?php
$i=null;
$search=null;
$result_query=null;
if(isset($_POST['search'])){
$get_value = addslashes($_POST['search']);
$search = mysqli_real_escape_string($con,"$get_value");
?>
<h2>Showing results for
<?php echo $_POST['search'] ?></h2>
<?php
if($search==''){
echo "<center><b>Please write something in the search box!</b></center>";
exit();
}
$search = $_POST['search'];
$terms = explode(" ", $search);
foreach ($terms as $each) {
$i++;
if ($i == 1)
$result_query .= "keywords LIKE '%$each%' ";
else
$result_query .= "OR keywords LIKE '%$each%' ";
}
$result_query = "SELECT * FROM content WHERE keywords LIKE '%".$search."%'";
$run_result = mysqli_query($con,$result_query);
// echo mysqli_num_rows($run_result);
// exit;
if(mysqli_num_rows($run_result)<1){
echo "<center>Sorry no matches found</center>";
exit();
}
while($row_result=mysqli_fetch_array($run_result))
{
$name=$row_result['name'];
$keywords=$row_result['keywords'];
$image=$row_result['image'];
$link=$row_result['link'];
?>

Related

highlight multiple keywords in search (PHP)

I am using this code to highlight search keywords:
<form method="post">
<input type="text" name="keyword" value="<?php if(isset($_GET["keyword"])) echo $_GET["keyword"]; ?>" />
<input type="submit" name="submit" value="Search" />
</form>
<?php
if(isset($_GET["keyword"]))
{
$condition = '';
$query = explode(" ", $_GET["keyword"]);
foreach($query as $text) { $condition .= "name LIKE '%".mysqli_real_escape_string($conn, $text)."%' OR "; }
$condition = substr($condition, 0, -4);
$sql_query = "SELECT * FROM products WHERE " . $condition;
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo ''.$row["name"].'';
}
}
else { echo '<label>Data not Found</label>'; }
}
?>
However, this highlights only one "keyword".
If the user enters more than one keyword, it will narrow down the search but no word is highlighted. How can I highlight more than one word?
For multiple search with like should use regexp
For example
SELECT * from products where name REGEXP 'apple|table';

How to select certain term depending on search?

So I am wanting the user to be able to search by either keyword or ID number. If they search "test" right now for example it will pull all the entries with test which is what I want it to do for the keyword part of the search. However, I also want the user to be able to search my specific a specific ID# and just pulling that specific entry. I am unsure how I would go about doing this. I tried doing some sort of OR statement but it did not pull any entries.
Search box form
<div class ="search" id="browse">
<p> Find your appointment below or search by keyword</p>
<form id="" class="searchbar" action="searchAppt.php" method="get">
<input type="text" name="terms" size="40" class = "sbar" placeholder="Search by issue keyword or ID" oninput="validity.valid||(value='');"
onblur="if (this.value == '') {
this.value = 'Enter keyword or ID';
}"
onfocus="if (this.value == 'Enter keyword or ID') {
this.value = '';
}"/>
<button type="submit" class = "btn">Search</button>
</form>
</div>
searchAppt.php
if (filter_has_var(INPUT_GET, "terms")) {
$terms_str = filter_input(INPUT_GET, 'terms', FILTER_SANITIZE_STRING);
} else {
echo "There were no appointments found.";
include ('includes/footer.php');
exit;
}
//explode the search terms into an array
$terms = explode(" ", $terms_str);
$sql = "SELECT * FROM appointments WHERE 1";
foreach ($terms as $term) {
$sql .= " AND email = '". $_SESSION['email'] ."' AND issue LIKE '%$term%' OR id ='%term%'
";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<br /><br /><center><h1>My Ticket(s)</h1><br />
<div class='table'>
<div class='tr'>
<div class='td'><b>Ticket #</b></div>
<div class='td'><b>Issue</b></div>
<div class='td'><b>Date</b></div>
<div class='td'><b>Ticket Details</b></div>
</div>";
// output data of each row
while($row = $result->fetch_assoc()) {
$starttimepast = strtotime($row["start_time"]); //converts date time received from MySQL into a string
$datepast = date("m/d/y", $starttimepast);
echo "<div class='tr'>
<div class='td'>".$row["id"]."</div>
<div class='td'>".$row["issue"]."</div>
<div class='td'>".$datepast."</div>
<div class='td'><form action='ticketdetails.php' method='post'>
<input type='hidden' name='id' value='".$row["id"]."'>
<input type='submit' value='Ticket Details'></form>
</div>
</div>";
}
echo "</div>";
echo "<br /><center><a href='myProfile.php'><h4>Go back to my profile</h4></a></center>";
include ('includes/footer.php');
} else {
echo "<br /> <br /><center><h3>Your search <i>'$terms_str'</i> did not match any appointments</h3></center>";
echo "<center><a href='myProfile.php'><h4>Go back to my profile</h4></a></center>";
echo "<br />";
exit;
}
?>
<?php
// clean up resultsets when we're done with them!
$query->close();
// close the connection.
$conn->close();
Perhaps it will help to explicitly group the terms:
$sql = "SELECT * FROM appointments WHERE email = '" . S_SESSION['email'] . "'";
$exprs = array();
foreach ($terms as $term) {
$exprs[] = "(issue LIKE '%$term%' OR id LIKE '%$term%')";
}
if (!empty($exprs)) {
$sql .= ' AND (' . join(' OR ', $exprs) . ')';
}
The result in this case will include records that matched any of the terms.
Note: It would be good to use a DB API like laravel/PDO/mysqli to simplify the query building and properly escape the values.

Undefined index: submit in E:\xampp\htdocs\FA2\search.php on lin

Undefined index: submit in E:\xampp\htdocs\FA2\search.php on line2
<?php
$button = $_GET [ 'submit' ];
$search = $_GET [ 'search' ];
if( !$button )
echo "you didn't submit a keyword";
else {
if( strlen( $search ) <= 1 )
echo "Search term too short";
else {
echo "You searched for <b> $search </b> <hr size='1' > </ br > ";
mysql_connect( "localhost","root","") ;
mysql_select_db("fa");
$search_exploded = explode ( " ", $search );
$x = 0;
foreach( $search_exploded as $search_each ) {
$x++;
$construct = "";
if( $x == 1 )
$construct .="keywords LIKE '%$search_each%'";
else $construct .="AND keywords LIKE '%$search_each%'";
}
$construct = " SELECT * FROM schoolname WHERE $construct ";
$run = mysql_query( $construct ); $foundnum = mysql_num_rows($run);
if ($foundnum == 0)
echo "Sorry, there are no matching result for <b> $search </b>. </br> </br> 1. Try more general words. for example: If you want to search 'how to create a website' then use general keyword like 'create' 'website' </br> 2. Try different words with similar meaning </br> 3. Please check your spelling";
else {
echo "$foundnum results found !<p>";
while( $runrows = mysql_fetch_assoc( $run ) ) {
$title = $runrows ['title'];
$desc = $runrows ['description'];
$url = $runrows ['url'];
echo "<a href='$url'> <b> $title </b> </a> <br> $desc <br> <a href='$url'> $url </a> <p>";
}
}
}
}
?>
Form code:
<form action="search.php" method="get" enctype="multipart/form-data">
<input class="wow fadeInRight" data-wow-delay="0.5s" type="text" name="search" placeholder="Seach School Here" required/>
<input class="wow fadeInLeft" data-wow-delay="0.5s" type="submit" value="GET STARTED" name="submit"/>
</form>
When you do the get request it looks like the submit value is not set, this makes is null and you get that error.
First check
isset
:
<?php
if(isset($_GET)){
$button = $_GET [ 'submit' ];
$search = $_GET [ 'search' ];
if( !$button )
......
....
.....
}
As #Sami Kuhmonen said, the fault was enctype="multipart/form-data"...
This only works for POST data, because you can't send a file trough GET
So the form should be:
<form action="search.php" method="get">
<input class="wow fadeInRight" data-wow-delay="0.5s" type="text" name="search" placeholder="Seach School Here" required/>
<input class="wow fadeInLeft" data-wow-delay="0.5s" type="submit" value="GET STARTED" name="submit"/>
</form>
First of all remove those spaces
$_GET['submit'] to $_GET['submit']
And instead use
$_REQUEST['submit']
It contains all parameters submitted via GET or POST method

Search Bar with Location dropdown sumit both results - PHP / mySQL

I have a basic search bar that searches my database using keywords (k). I am trying to submit both location and search result but the problem is when I submit the search results I get "search.php?k=builder&k=New+York" and not "search.php?k=builder+New+York" how do I correct this?
HTML
<form action="search.php" method="get" style="margin:0 auto; text-align:center;">
<input type="text" name="k" size="10" style="width:40%;"/>
<div id="the-basics">
<input class="typeahead" type="text" name="k" placeholder="States of USA">
</div>
<input type="submit" value="Search" style="width:100px;">
</form>
Search Bar PHP Code:
<?php
if(!empty($_GET['k'])){
//if search bar is empty
}else{
echo "'<meta http-equiv='refresh' content='0;url=index.php'>";
//redirect back to index.php
}
$k = $_GET['k']; //k stands for keyword
$i = 0;
$terms = explode(" ", $k);
$query ="SELECT * FROM record WHERE ";
foreach ($terms as $each) {
$i++;
if ($i == 1)
$query .= "company_name LIKE '%$each%' " . "OR website LIKE '%$each%' " . "OR email LIKE '%$each%' " . "OR tel LIKE '%$each%' " . "OR description LIKE '%$each%'" . "OR location LIKE '%$each%'" . "OR description LIKE '%$each%'";
}
$connection = mysql_connect('localhost', 'username', 'password');
mysql_select_db('DB_name');
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0){
while ($row = mysql_fetch_assoc($query)) { { ?>
..........search result shows here........
Hi you need appaly some JS
<script>
function submitForm(obj){
var search = $('input[name="k"]).val();
var state= $('#state').val();
$('input[name="k"]).val(search+" "+state )
obj.submit();
}
</script>
<form action="search.php" method="get" style="margin:0 auto; text-align:center;" onsubmit=submitForm(this)>
<input type="text" name="k" size="10" style="width:40%;"/>
<div id="the-basics">
<input class="typeahead" type="text" id="state" placeholder="States of USA">
</div>
<input type="submit" value="Search" style="width:100px;">
</form>

Multiply word search

I have made a simple search engine that can search my database. It works this way: you check the word you want to search for in a checkbox. Result are sent using a form. The issue is that it only searches for the last word checked. This mean do I check 3 words it’s only showing results for the last word checked. Here is my form:
<form method="POST" action="<?=$_SERVER["PHP_SELF"]?>">
<p>Search for:
</p>
Books: <input type="checkbox" name='search' value="Books">
Movies: <input type="checkbox" name='search' value="Movies">
Outdoor: <input type="checkbox" name='search' value="Outdoor">
Indoor: <input type="checkbox" name='search' value="Indoor">
</p>
<p><input type='submit' value='Search'></p>
</form>
This is my codes that generate the result:
<?php
if(isset($_POST['search']))
{
$connx = mysql_connect('localhost', 'USER', 'PASSWORD') or die("connx");
$db = mysql_select_db('DB_NAME') or die(mysql_error());
# convert to upper case, trim it, and replace spaces with "|":
$search = (ini_get('magic_quotes_gpc')) ? stripslashes($_POST['search']) :
$_POST['search'];
$search = mysql_real_escape_string($search);
$search = strtoupper(preg_replace('/\s+/', '|', trim($_POST['search'])));
# create a MySQL REGEXP for the search:
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
$query = "SELECT * FROM `galleries` WHERE UPPER(`keywords1`) $regexp OR ".
"`keywords2` $regexp";
$result = mysql_query($query) or die($query . " - " . mysql_error());
echo "<table>\n";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td><img src=../thumbs/{$row['type']}/{$row['folder']}/{$row['date']}-{$row['num']}/{$row['thumbimage']} border=1></td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['date']}</td>";
echo "<td><a href=../view.php?id={$row['id']} target=blank>View</a></td>";
echo "</tr>\n";
}
}
?>
Can someone help me telling me how do I get the search engine to search and/or show more than 1 word searched result?
You have input fields with same name therefore you are getting the last one you need to make the array for search fields like name="search[]" and the loop through your query against the array values
Books: <input type="checkbox" name='search[]' value="Books">
Movies: <input type="checkbox" name='search[]' value="Movies">
Outdoor: <input type="checkbox" name='search[]' value="Outdoor">
Indoor: <input type="checkbox" name='search[]' value="Indoor">
something like this
$regexp ="";
$searharray =$_POST['search'];
$count=count($searharray);
$index=1;
foreach($searharray as $s){
$s = (ini_get('magic_quotes_gpc')) ? stripslashes($s) :$s;
$s= mysql_real_escape_string($s);
$s = strtoupper(preg_replace('/\s+/', '|', trim($s)));
$regexp .= " UPPER(`keywords1`) REGEXP '[[:<:]](".$s.")[[:>:]]' OR `keywords2` REGEXP '[[:<:]](".$s.")[[:>:]]'";
if($index<$count){
$regexp .=" OR ";
}
$index++
}
$query = "SELECT * FROM `galleries` WHERE $regexp";
Problem fixed! I replaced the 2 lines:
$search = mysql_real_escape_string($search);
$search = strtoupper(preg_replace('/\s+/', '|', ($_POST['search'])));
With:
$search = implode( '|', $_POST['search'] );
And now its working - just if anyone else should need the info :)

Categories