Search function for multiple fields in PHP - php

I am making a Search function in PHP MySQL. Currently, my code is working but when trying to search by date, all content appear. It seems that the 2 fields aren't connected.
Please help. Thanks.
<?php
$query = $_GET['query'];
$date = $_GET['date'];
// gets value sent over search form
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM tblArchive WHERE (Author LIKE '%".$query."%' OR Title LIKE '%".$query."%' or Content LIKE '%".$query."%' AND Date LIKE '%".$date."%')");
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['Title']."</h3>"."<h3>".$results['Author']."</h3>"."<h4>".$results['Date']."</h4>".$results['Content']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>

$raw_results = mysql_query(
"SELECT * FROM tblArchive
WHERE (Author LIKE '%".$query."%'
OR Title LIKE '%".$query."%' or Content LIKE '%".$query."%')
AND (Date LIKE '%".$date."%')");
Please Try This Query It will work fine.

$get = 'SELECT * FROM tblArchive';
if(!empty($query)){
$get .= ' WHERE (Author LIKE '%".$query."%' OR Title LIKE '%".$query."%' or Content LIKE '%".$query."%' ';
}
if(!empty($date) && !empty($query)){
$get .= " And Date LIKE '%".$date."%'";
}
else{
$get .= " Where Date LIKE '%".$date."%'";
}
$result = mysql_query($get);

Related

Auto complete suggestion box are not working properly?

code:
<?php
include('config.php');
$return_arr = array();
$term = $_GET['term'];
$term = str_replace('.','',$term);
$sql = "SELECT * FROM submission where keyword like '%".$term."%' or companyname like '%".$term."%' ORDER BY CASE WHEN keyword LIKE '%".$term."%' THEN 1
ELSE 2 END";
$r = mysqli_query($link,$sql);
while($row = mysqli_fetch_assoc($r))
{
$key = explode(",", $row['keyword']);
foreach ($key as $keyword)
{
$return_arr[] = $keyword;
}
}
echo json_encode($return_arr);
?>
In my code I have created a auto complete suggestion box and its working but it always showing wrong result if I write (i) it always show result with (a) alphabet why not (i) and also want to search with short name. So, How can I do this ?Please help me.
Thank You
if you want to compare result start with input character then remove % from beginning
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";
You used %$term% in your query. So whether the data store the searched keyword anywhere in the string, it will display to you. So if you want to search the data start with a specific character remove % from the start of your query to make it as $term% as
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";

Php script to search a record from database by name. (filter by name)

Can someone correct the code for filter a record by its name. I know the query but perhaps I'm not implementing it properly.
Here is my code. I want to either search by city or simply put a name in textbox to search an hospital. search-by-name is for an input field where I am supposed to write the name I want to search from database. I want to make both options available. How should I implement it correctly, as this one won't work for me.
if (isset($_POST['search'])) {
if (isset($_POST['search-by-city'])) {
$city_id = $_POST['search-by-city'];
$query = "SELECT * FROM `hospitals` WHERE `City_ID` LIKE '$city_id'";
$result = mysqli_query($con,$query);
if (isset($_POST['search-by-name'])) {
$hospital_name = $_POST['search-by-name'];
$query = "SELECT * FROM `hospitals` WHERE `Name` LIKE '$hospital_name'";
$result = filterTable($query); {
if (mysqli_num_rows($result) == 0) {
echo '<div class="col-md-12"> <h2>No recod Found</h2> </div> ';
}
}
}
while($row = mysqli_fetch_array($result)){
$city_id = $row[3];
$query = "SELECT `Name` FROM `cites` WHERE `ID` LIKE '$city_id'";
$result2 = mysqli_query($con,$query);
$row2 = mysqli_fetch_row($result2);
$city_name = $row2[0];
echo '<div class="col-md-4"><h3>'.$row[1].'</h3><h4>'.$city_name.'</h4><h4>'.$row[2].'</h4><h5>'.$row[3].'</h5><h5>'.$row[4].'</h5>
';
}
}
I'm guessing your query should be:
"SELECT * FROM `hospitals` WHERE `Name` LIKE '%$hospital_name%'
Checkout the mySQL manual on string comparison.
Also please don't use $_POST variables directly in SQL queries, that is a major security issue. (Search for sql-injection.)

Change + to an & in search string

I'm pretty new to PHP and have this script that I am using to search a database I have for jobs. The problem is when the query arrives to this script it looks something like this search-result.php?query=engineer+sydney ... However, I need search for both words together and appear like this search-result.php?query=engineer&sydney with the & instead of the +
Is this something I should be trying to do from the search form or within the search script itself? I've added the search script below and the form below that.
Any help would be great!
<div class="joblist">
<?php
$query = $_GET['query'];
$query = sanitise($query);
// gets value sent over search form
$min_length = 3;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM job_jobs
WHERE (`description` LIKE '%".$query."%') OR (`summary` LIKE '%".$query."%') OR (`title` LIKE '%".$query."%') OR (`location` LIKE '%".$query."%') ") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `title`, `text`
// articles is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<h3 style='padding:0;margin:0;'><a href='job-view.php?query=".$results['jid']."'>".$results['title']. "</a></h3>";
echo "<i style='color:#999;'>Posted on: " . date("jS M Y", strtotime($results['dateposted']))."</i><br/>" . $results['summary'] . "<br/>";
echo "Salary: " . $results['rate'] . " | Work Type: " . $results['worktype'] . " | Location: " . $results['location'];
echo "<br/><br/>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
}
else{ // if there is no matching rows do following
echo "<h3>No Results</h3>Your search returned no results. Please try again.";
}
}
else{ // if query length is less than minimum
echo "<h3>Error</h3>The minimum length is $min_length characters. Please try again.";
}
?>
</div>
<nav class="widget-search">
<h3>Search for a Job</h3>
<form action="search-result.php" method="GET">
<button class="search-btn-widget"></button>
<input class="search-field" type="text" name="query" onblur="if(this.value=='')this.value='eg. Civil Engineer Perth';" onfocus="if(this.value=='eg. Civil Engineer Perth')this.value='';" value="eg. Civil Engineer Perth" />
</form>
</nav>
whenever you send data using GET method it forms a NAME=VALUE pair.and the '+' you are seeing is whitespace which some browser use % or some may use + also.
query=engineer+sydney
----^name-------^value
$query = $_GET['query'];
$query =str_replace(" ","&",$query);
now what you can do is fetch the query value and replace the whitespace with '&' or whatever sign you want
$result = str_replace('+','&',$_GET["query"]);
echo $result;
Thanks
break your query variable with space
$arr_query = explode(" ",$query);
now make a dynamic where
$where = ""
$i=0;
foreach($arr_query as $val)
{
$i+=1;
if($i==1)
{
$where .= " WHERE (`description` LIKE '%".$val."%') OR (`summary` LIKE '%".$val."%') OR (`title` LIKE '%".$val."%') OR (`location` LIKE '%".$val."%') ";
}
else
{
$where .= " AND (`description` LIKE '%".$val."%') OR (`summary` LIKE '%".$val."%') OR (`title` LIKE '%".$val."%') OR (`location` LIKE '%".$val."%') ";
}
}
now you can use this $where in you query as follows.
$raw_results = mysql_query("SELECT * FROM job_jobs $where ") or die(mysql_error());

php searching multiple fields on msql and return exactly answer

my be i may change the question explanation since no any help,But I real want help.
I have a search box in my form which enable user to search student data in mysql table, I only succeed on searching single field eg (first name or second name or sir name) the BIG problem to me is how to search multiple field on the same text input field or any number of text input field eg(text1, text2, text3) only I want is to have exactly result. Sorry if any mistake.
Here the php codes I use to get single field search.
<html>
<head></head>
<body><input type="text" name="query" value=""/>
<input name="submit" type="submit" value="Search" />
<?php
$query="query";
//mysql_connect
$query='query';
if (isset($_GET['query']))
{
$query=$_GET['query'];
// Instructions if $_POST['value'] exist
}
$raw_results = mysql_query("SELECT * FROM stdreg_exam
WHERE (`fname` LIKE '%".$query."%') or (`secname` LIKE '%".$query."%')or
(`date` LIKE '%".$query."%') or (`surname` LIKE '%".$query."%')") or
die(mysql_error());
$raw_results2 = mysql_query("SELECT(idnumber) FROM student
WHERE (`fname` LIKE '%".$query."%') or (`secname` LIKE
'%".$query."%') or (`date` LIKE '%".$query."%')or
(`surname` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `title`, `text`
// articles is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
if(mysql_num_rows($raw_results) > 0){
// if one or more rows are
returned do following
while($results = mysql_fetch_array($raw_results)){
while($results2 = mysql_fetch_array($raw_results2)){
// $results = mysql_fetch_array($raw_results) puts data from database into
array, while it's valid it does the loop
echo "<table width='750' height='5' cellpadding='2'
cellspacing='0' border='0'>";
echo"<tr><td>Std_id</td><td>Mathematics</td><td>English</td>
<td>Kiswahili</td><td>Geograph</td><td>Ict</td><td>Science</td>
<td>History</td><td>Pds</td><td>V skill</td><td>French</td>
<td>Religion</td><td>Civics</td>";
echo "<h4> ".$results['exam_name']." Examination result for
" .$results['fname']." " .$results['secname']
." ".$results['surname']." ".$results['class']." Class"."
held on</p>".$results['date']."<hr><th>"; echo"<tr>";
echo ""."<td>".$results2['idnumber'].""."<td>".$results['mathematics']."%"."
<td>".$results['english']."%"."<td>".$results['kiswahili']."%"."
<td>".$results['geograph']."%"."<td>".$results['ict']."%"."
<td>".$results['science']."%"."<td>".$results['history']."%"."
<td>".$results['pds']."%"."<td>".$results['vskill']."%"."
<td>".$results['french']."%"."<td>".$results['religion']."%"."
<td>".$results['civics']."%"."</td></p>";echo"</table>";
//posts results gotten from database(title and text) you can also show id
($results['id'])
}
}
}
else{
// if there is no matching rows do following
echo "No such information in School database";
}
}
else{
// if query length is less than minimum
echo "Enter more strings!!!Minimum length is ".$min_length; "Charactes";
}
?>
If you have 3 text fields, let's say text1, text2 and text3 and you need to get search result from DB. You could try something like this
$query = "SELECT your_feilds,another_fields FROM your_table WHERE 1=1 ";
if($_POST['text1'])
$query .= " AND text1_field like '%$_POST['text1']%' ";
if($_POST['text2'])
$query .= " AND text2_field like '%$_POST['text2']%' ";
if($_POST['text3'])
$query .= " AND text3_field like '%$_POST['text3']%' ";
$result = mysql_query($query);
The above answer from #Shafeeq is very functional and is working as I have used the same approach for one of my applications, but there is one issue, if you have a another field let us say date and you want to search between two dates.
The query will be like that
if($_POST['from_date'] && $_POST['To_date'])
$query .= " AND date between '$from_field' AND '$To_field' ";
Then It does not work for other fileds

Make the PHP MySql Search Engine and Pagination work

I don't know how to make the search through another table. how should i do that?
the table name is comments and i want to search for all the post stored in the column name kom
Another thing is that i cant get the pagination start working...
I started the pagination within an else statment because i only need it when i get more than 1 result.
I can get the page links showing and limit the search posting showing but when i click on one off the links i cant get to the next page
Heres the code
<?php
$search = $_POST["search"];
$field = $_POST["field"];
if($_POST["submit"] && $search)
{
echo "<div id='result'>";
echo "<h2>Resultat</h2>";
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);
$query = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%'";
$result = mysql_query($query, $conn) or die(mysql_error());
$matches = mysql_num_rows($result);
if($matches == 0)
//code if serch didnt result any results
else if($matches == 1)
//code if the matches only 1
else
{
$per_page = 4;
$pages = ceil($matches / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page']: 1;
$start = ($page - 1) * $per_page;
$query2 = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%' LIMIT $start, $per_page";
$result2 = mysql_query($query2, $conn) or die(mysql_error());
echo "<font size='-1'>Sökningen $search gav $matches resultat</font><br/>";
while ($r2 = mysql_fetch_array($result2))
{
$id = $r["id"];
$title = $r["title"];
$post = $r["post"];
$time = $r["time"];
echo "<br/><strong><a href='comment.php?id=$id'>$title</a></strong><br/>";
echo "<font size='-1'>".substr($post, 0, 60)."</font><br/>";
echo "<font size='-1'>".substr($post, 60, 70)."</font><br/>";
echo "<font size='-3'>$time</font><br/>";
}
//theese are showin but cannot click of any of them
if($pages >= 1 && $page <= $pages)
{
for($nr = 1; $nr <= $pages; $nr++)
{
if($nr == $page)
echo "<a href='?page=".$nr."' style='font-size:20px;'>$nr</a>";
else
echo "<a href='?page=".$nr."' style='font-size:15px;'>$nr</a> ";
}
}
}
}
?>
Is there a specific reason you are using a UNION?
If not, you can change:
$query = "SELECT * FROM blogTable WHERE title LIKE '%$search%'
UNION
SELECT * FROM blogTable WHERE post LIKE '%$search%'";
to:
$query = "SELECT * FROM blogTable WHERE (title LIKE '%$search%') OR (post LIKE '%$search%')";
Anyway, I would never execute the same query twice, just get the first x results if no start parameter was given (for example a page number in the query string) and calculate the start point when a start parameter was given.
And if you want the total, use a COUNT(*) query or change your query:
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM blogTable WHERE (title LIKE '%$search%') OR (post LIKE '%$search%')";
One thing that catches the eye is that the code you show is vulnerable to SQL injection.
Get rid of the strip_tags() (if it's for security, in which case it's useless) and do a mysql_real_escape_string() on every value you use in the search queries, or check whether the value is actually a number when using int columns.
Another thing is that the <font> tag is outmoded. The cool CSS way of styling text is having an external CSS stylesheet, and defining in it something like
span.small { font-size: 12px; color: green }
and then using it in the HTML like so:
<span class="small">Text goes here</span>
that said, this probably belongs on CodeReview.SE....
First, I always recommend to use GET method and not POST method for searches and filters, next, maybe this pagination php class can help you.

Categories