highlight multiple keywords in search (PHP) - 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';

Related

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.

How to use searching method using a select tag option to search id,email,username in PHP, MYSQL?

Hello I'm trying to get a searching method using select tag with an option of ID,Email, and Fullname.
I have this html code for search:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<select class="searchoptionuser" name="Search" id="searchbyuser">
<option value="" disabled selected value>Search User</option>
<option value="ID">ID</option>
<option value="Email">Email</option>
<option value="Fullname">Fullname</option>
</select>
<input type="text" name="search" placeholder="Search..." id="search_text" class="searchtext">
<input type="submit" name="submit" value="Search">
</form>
And I want to filter the search when I select the ID, the search will only search by ID and also Email and Fullname.
I've tried this in PHP:
<?php
include "includes/connection.php";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['Search']) == "ID")
{
// query code here from database
alert(1);
} else if(isset($_POST['Search']) == "Email") {
// query code here from database
} else if(isset($_POST['Search']) == "Fullname") {
// query code here from database
$output = "";
$sql = "SELECT * FROM user WHERE firstname LIKE '%".$_POST["search"]."%' or lastname LIKE '%".$_POST["search"]."%'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
$output .= "<tr><th>User ID</th><th>Email</th><th>Fullname</th><th>Phone Number</th></tr>";
// output data of each row
while($row = mysqli_fetch_array($result)) {
$output .= "<tr>
<td>" .$row["id"]. "</td><td>" .$row["email"]. "</td><td>" .$row["lastname"]. ", " .$row["firstname"]. "</td><td>" .$row["phonenumber"]. "</td>
</tr>";
}
echo $output;
} else {
echo "No account found.";
}
}
}
?>
But it doesn't seem to work.. Is this possible in php or this method is only for javascript or jquery. Please help anyone. Thanks
You can create a conditional query based on the data you get from $_POST.
$query = "";
if($_POST['Search'] == "ID")
{
$query .= "AND firstname LIKE '%".$_POST["search"]."%' or lastname LIKE '%".$_POST["Search"]."%'"";
} else if($_POST['Search'] == "Email") {
$query .= "AND email LIKE '%".$_POST["Search"]."%'";
} else if($_POST['Search'] == "Fullname") {
$query .= "AND ID = ".$_POST["Search"];
}
$sql = "SELECT * FROM user WHERE 1=1 ".$query ;
Please ignore syntax errors if any as I have not tested the code but it will give you an idea how you can achieve it.

Searching multiple terms with 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'];
?>

How can I create a PHP Advanced Search using a simple HTML form with PHP and MySQL?

I want for my users to be able to search for multiple criteria from the search form.
Here is the HTML:
<form id="form_search" action="search.php" method="post">
<input class="search" type="text" name="search" placeholder="Search for a property for sell or rent" autocomplete="off">
<select name="min_val" class="control_option option_select min_val">
<option selected>Property Type</option>
<option>Homes for Sale</option>
<option>Homes to Let</option>
<option>Student Accomodation</option>
<option>Commercial</option>
<option>Land and Sites</option>
<option>Auctions</option>
<option>Agricultural</option>
</select>
<select name="max_val" class="control_option option_select max_val">
<option selected>Max Price</option>
<option>£25,000</option>
<option>£50,000</option>
<option>£100,000</option>
<option>£150,000</option>
<option>£200,000</option>
<option>£250,000</option>
<option>£300,000</option>
<option>£350,000</option>
<option>£400,000</option>
<option>£450,000</option>
<option>£500,000</option>
<option>£600,000+</option>
</select>
<select name="beds" class="control_option no_bed">
<option selected>Bedrooms</option>
<option>1 Bedroom</option>
<option>2 Bedrooms</option>
<option>3 Bedrooms</option>
<option>4 Bedrooms</option>
<option>4+ Bedrooms</option>
</select>
<input class="search_btn" name="search_button" type="submit" value="Search" />
</form>
I can get it to search my database okay, but I am stumped for getting it to search for multiple things at once.
Here is the PHP:
<?php
$search = $_GET['search'];
$terms = explode(" ", $search);
$query = "SELECT * FROM test WHERE";
foreach ($terms as $each) {
$i++;
if ($i == 1)
$query .= " keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
if ($i == 1)
$query .= " price BETWEEN 0 AND '%$each%'";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_array($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$price = $row['price'];
$link = $row['link'];
echo "<h1>$title</h1><br />
$description<br />$price<hr />";
}
} else {
echo "<b>Sorry we found no properties matching '$search', please try another term.</b>";
}
mysql_close();
?>
This is arough idea about how to proceed. there are better way to write this with function.
<?php
$search = $_GET['search'];
$min_val = $_GET['min_val'];
$max_val = $_GET['max_val'];
//$terms = explode(" ", $search);
$query = "SELECT * FROM test WHERE";
$init=1;
if (isset($search) ){
$query .= (($init==1)?'':' OR ')." keywords LIKE '%$each%' ";
$init=($init==1)?0:$init;
}
if (isset($min_val) ){
$query .= (($init==1)?'':' OR ')." price BETWEEN $min_val AND '$max_val' ";
$init=($init==1)?0:$init;
}
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0 ) {
while ($row = mysql_fetch_array($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$price = $row['price'];
$link = $row['link'];
echo "<h1>$title</h1><br />
$description<br />$price<hr />";
}
} else {
echo "<b>Sorry we found no properties matching '$search', please try another term.</b>";
}
mysql_close();
?>

Empty search result when trying to create PHP search script

why when i try to search mysql database, it shows 0 result? i altered the table into FULLTEXT etc properly. What am I missing? I have put the very basic search exercise code down here. I want to search into my table 'products' and extract the details from there. but no luck
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$search_output = "";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
$searchquery = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['searchquery']);
if($_POST['filter1'] == "Whole Site"){
$sqlCommand = "SELECT product_name AS name, details AS details FROM products WHERE MATCH (product_name ,details) AGAINST ('$searchquery' IN BOOLEAN MODE)";
}
require_once("storescripts/connect_to_mysqli.php");
$query = mysqli_query($myConnection,$sqlCommand) or die(mysqli_error($myConnection));
$count = mysqli_num_rows($query);
if($count > 1){
$search_output .= "<hr />$count results for <strong>$searchquery</strong><hr />$sqlCommand<hr />";
while($row = mysqli_fetch_array($query)){
$name = $row["name"];
$details= $row["details"];
$search_output .= "Name: '.$name.' - '.$details.'<br />";
} // close while
} else {
$search_output = "<hr />0 results for <strong>$searchquery</strong><hr />$sqlCommand";
}
}
?>
<html>
<head>
</head>
<body>
<h2>Search the Exercise Tables</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Search For:
<input name="searchquery" type="text" size="44" maxlength="88">
Within:
<select name="filter1">
<option value="Whole Site">Whole Site</option>
</select>
<input name="myBtn" type="submit">
<br />
</form>
<div>
<?php echo $search_output; ?>
</div>
</body>
</html>
Change this:
$sqlCommand = "SELECT product_name AS name, details AS details FROM products WHERE MATCH (product_name ,details) AGAINST ('".$searchquery."' IN BOOLEAN MODE)";
i have changed
AGAINST ('$searchquery' IN
to
AGAINST ('".$searchquery."' IN
Problem is there with your if part as:
replace your current :
if($_POST['filter1'] == "Whole Site")
{
$sqlCommand = "SELECT product_name AS name, details AS details FROM products WHERE MATCH (product_name ,details) AGAINST ({$searchquery} IN BOOLEAN MODE)";
}
In case it couldnt get to query due to if statement add:
else {
echo "No seqrch query found";
}
hope it works now

Categories