Multiply word search - php

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

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

Multiple checkbox search query fetching data from database in php

I have a multiple checkbox search query which fetches data from database. Below is the code:
HTML code:
<form action="search.php" method="post">
<input type="checkbox" name="cloth_color[]" value="Red" /> Red <br>
<input type="checkbox" name="cloth_color[]" value="Yellow" /> Yellow <br>
<input type="checkbox" name="cloth_color[]" value="Blue" /> Blue <br>
<input type="checkbox" name="cloth_color[]" value="Green" /> Green <br>
<input type="checkbox" name="cloth_color[]" value="Magenta" /> Magenta <br>
<input type="checkbox" name="cloth_color[]" value="Black" /> Black <br>
<input type="checkbox" name="cloth_color[]" value="White" /> White <br>
<input type="submit" value="SEARCH">
</form>
PHP code:
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1;
}
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
}
?>
Now if I choose one option from the search select box I get query. But if I select two or more color I dont get the query. A help will be really appreciated.
P.S. I do have multiple joins in Mysql query but this is the place I am stuck so presenting as clear question as possible here. Also I intent to convert mysql to mysqli before the launch of this code. Thank you :)
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1 . ",";
}
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($chk)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
?>
you can try this code which will use IN() of MySQL where you can pass multiple , separated values.
Hope this helps
Ok this is what i did. first of all got great help from #Dhaval and #Carlos as wasn't familiar with IN function in Mysql.
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= "'" . $chk1."', ";
//This is important as it is not the number it is a word so it should have a single quote if in query we are using double quote or vice versa.
}
$check_e = rtrim($chk,", ");
//Although i havn't checked in real time if mysql query will take last comma or not but it is a good practice to remove the last comma by rtrim.
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($check_e)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
?>
What you may want to use is the Mysql IN CLause.
For this example, i am assuming that you use the correct syntax for the elements inside de IN Clause.
The correct syntax would be all the values that you need separated by commas, if you select red and blue.
$chk = 'red, blue'
Using the 'IN Clause' this query
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
should transform to this.
$query = "SELECT * FROM clothings WHERE colorofcloth IN ('$chk')";
I do not know much about PHP, but for a database stand it should work.
Let me know if it works.

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'];
?>

MySQL search enquiry error

I am trying to create a form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and finally by event title, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, but it seems to output every single event from the database no matter what I type in the search field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value = '$venueID'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<input type="checkbox" name="S_venueName">
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catID'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
searchfunction.php file
<?php
$count = 0;
include 'database_conn.php';
$venuename = $_REQUEST['venueName']; //this is an integer
$catdesc = $_REQUEST['catdesc']; //this is a string
$Price = $_REQUEST['S_price'];
$EventT = $_REQUEST['S_EventT'];
$sql = "select * FROM te_events WHERE venueID LIKE '%$venuename%' OR catID LIKE '%$catdesc%' OR eventPrice LIKE '%Price%' OR eventTitle LIKE '%$EventT%'";
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo $row['eventTitle'];
echo $row['eventDescription'];
echo $row['venueID'];
echo $row['catID'];
echo $row['eventStartDate'];
echo $row['eventEndDate'];
echo $row['eventPrice'];
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
The query should be
$sql = "select * FROM te_events
WHERE (venueID LIKE '%$venuename%'
OR catID LIKE '%$catdesc%'
OR eventPrice LIKE '%$Price%'
OR eventTitle LIKE '%$EventT%')
;
To get values from the form submitted with method POST we use $_POST to access form data and not $_REQUEST:
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
That was about your problem - now some important notes:
Do not use mysql extension as it's deprecated. Read this official documentation.
Use mysqli and prevent SQL injections by using prepared queries and parameters like in official documentation again.
Since you are matching on any fields surrounded by wildcards, if any of the fields are blank, then the MySQL query will match all rows.
Also, you need to prevent MySQL injection. Otherwise, your MySQL table will eventually be hacked.
By the way, the code eventPrice LIKE '%Price%' is invalid and is missing a dollar sign.
Lastly, the mysql extension has been deprecated. I would recommend using mysqli instead as it is fairly similar.

How to create a semantic search

I want to create a search box where instead of using a WHERE cluse in the query to match the exact phrase within a field, I want the search box to be able to perform a semantic search so that when the user enters in part of a phrase, it displays suitable results where it is able to match the meaning of a phrase. Exactly how Google works when you try and search through Google. Is this possible to achieve and does anyone have any ideas?
Below is the code I am currently using to be able to use the database to see if a row matches the exact phrase entered within the search box:
<?php
//connected to DB
foreach (array('questioncontent') as $varname) {
$questioncontent = (isset($_POST[$varname])) ? $_POST[$varname] : '';
}
?>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post" id="modalform">
<p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
<?php
if (isset($_POST['searchQuestion'])) {
$questionquery = "SELECT QuestionContent FROM Question
WHERE(QuestionContent = '".mysql_real_escape_string($questioncontent)."')";
$questionnum = mysql_num_rows($questionresult = mysql_query($questionquery));
if($questionnum !=0){
$output = "";
while ($questionrow = mysql_fetch_array($questionresult)) {
$output .= "
<table>
<tr>
<td>{$questionrow['QuestionContent']}</td>
</tr>";
}
$output .= " </table>";
echo $output;
}
}

Categories