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;
}
}
Related
I am quite new to PHP and have been following tutorials and notes so far and have run into a problem.The goal is to create an e-commerce website. One function must be to search the database and display products which I can do. These results must then be able to be sorted (by price/name etc.) I can sort the products however I cannot sort the results f the search as I lose the searched term when reloading. Any help on fixing this or improving the work would be fantastic.
Here is what I have so far..
<div id = "form">
<form action="search3.php" method="get" enctype="multipart/form-data">
Search: <input type="text" name="term" /><br />
<input type="submit" name = "search" value="Submit" />
</form>
</div>
The form above stores "term" the searched term.
<?php
$term = pg_escape_string($_REQUEST['term']);?>
<p>You Searched for:</p><?php Print $term; ?>
<br><br>
Sort by
<form method=get style="display: inline;" name='orderby_form'>
<input type=hidden name='param1' value="<?php print $param1; ?>">
<input type=hidden name='param2' value="<?php print $param2; ?>">
<select name=orderby onChange="orderby_form.submit();">
<option value='none'>v-v-v</option>
<option value='title'>Title</option>
<option value='price_asc'>Price (Low - High)</option>
<option value='price_desc'>Price (High - Low)</option>
</select>
</form>
This gives options on how the user wants to sort the data
<?php
$selected = array();
$orderby = $_GET['orderby'];
if(!$orderby)
{ $orderby = ''; }
if($orderby == 'price_asc')
{
$orderby_query = "order by price asc";
}
else if($orderby == 'price_desc')
{
$orderby_query = "order by price desc";
}
else if($orderby == 'title')
{
$orderby_query = "order by title";
}
else { unset($orderby); }
// If $orderby was valid set the selected sort option for the form.
if($orderby)
{
$selected[$orderby] = 'selected';
}
// Now run your SQL query with the $orderby_query variable. Ex:
$query = "SELECT * FROM products WHERE (title LIKE '%$term%' OR description LIKE '%$term%') $orderby_query";
// SQL code goes here..
$result = pg_query($query);
if(pg_num_rows($result) == 0) {
echo "No records found";
}
else{
while ($row = pg_fetch_assoc($result)) {
?>
After the final bit here I just print the results into tables
These two pictures show the search results.
The first prints all products with "bass" in the title/description and is unsorted.
http://oi61.tinypic.com/28clzqs.jpg
The second is when I sort the data.The search 'term' is lost and ALL products become sorted.
http://oi59.tinypic.com/34g39tu.jpg
Simple enough work around. Thanks to Sean for showing me.
"add your $term to the 2nd form"
Which is
<input type=hidden name='param2' value="<?php print $param2; ?>">
//Added -VV-
<input type=hidden name='term' value="<?php print $term; ?>">
Works perfectly well now.
I am new to stack overflow and really appreciate all the help. I currently have a database with basic columns, name id company etc. I created a search query that shifts through this list based on firstname, lastname, or timestamp date. I was able to print the results on the query page of the search but want this to pre populate on the same form page as a new entry. i was able to link from the query page to the form page but am not sure how to populate these results on the form page.
my current query page prints as the following :
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div id="container" style="width:750px;background-color:#FFFE8D;margin-left: 250px">
<div id="Back" style="float:left; background-color:#FFFE8D;">
<form action="http://localhost/contractor/existingcontractorpage3.php">
<input type="submit" value="Back">
</form>
</div>
<div id="Is this the Contractor?" style="float:right; background-color:#FFFE8D;">
<form action="http://localhost/contractor/redirectcontractorpage.php">
<input type="submit" value="Next">
</form>
</div>
<div id="info" style="width:750px;height:95px; text-align: center">
<h3> If this is the contractor, please move on to the next page using the corresponding button above. </h3>
<h3> Please enter the exact information on the next page. </h3>
</div>
<div id="results" style="width:750px;height:225px; text-align: center">
<?php
$host = "localhost"; //server
$db = ""; //database name
$user = ""; //databases user name
$pwd = ""; //password
mysql_connect($host, $user, $pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$searchTerm = trim($_GET['searchname']);
// Check if $searchTerm is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
else
{
$sql = "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ', ARRIVAL) like '%$searchTerm%'";
$query = mysql_query($sql);
$count=mysql_num_rows($query);
if(($count)>=1)
{
$output = "";
while($row = mysql_fetch_array($query))
{
$output .= "First Name: " . $row['FIRSTNAME'] . "<br />";
$output .= "Last Name: " . $row['LASTNAME'] . "<br />";
$output .= "Arrival: " . $row['ARRIVAL'] . "<br />";
}
echo $output;
}
else
echo "There was no matching record for the name " . $searchTerm;
}
?>
</div>
<br> </br>
<br> </br>
</body>
</html>
Now ideally i would want the results to pop up here, and if possibly have a radio button to the right of each result( if there is ever more than one) to select and continue to the form page to pre populate each field. the form page is simply like this:
<form action="insert_submit.php" method="post">
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" />
<br>
</br>
Last Name: <input type = "text" name="LASTNAME" id="LASTNAME"/>
<br>
</br>
Purpose: <input type = "text" name="PURPOSE" id="PURPOSE"/>
<br>
</br>
Company: <input type = "text" name="COMPANY" id="COMPANY" />
<br>
</br>
Who here to see: <input type = "text" name="WHOHERETOSEE" id="WHOHERETOSEE"/>
<br>
</br>
<input type="submit" value="Submit">
<br>
</br>
</form>
thanks so much! hope to hear back soon as this is my last straw on my project.
The simplest way to do this is to pull the data from the database like you're doing, except where you want to add the form into the page. Then in your loop print out form fields:
You need to give each radio a unique name. You could use an incrementing id, or you could give it the same as the row name.
Method 1:
while($row = mysql_fetch_array($query))
{
$output .= "<label>First Name: " . $row['FIRSTNAME'] . "</label><input type=\"radio\" name = \"radio[]\" value=\"".$row['FIRSTNAME']." ".$row['LASTNAME']."\"/>";
..
..
}
You will then be able to get the values from the radio buttons by using GET or POST when the from is submitted.
Setting name = "radio[]" puts all the values in an array which you can get on the next page once the form is submitted.
On the next page after form submission, $_POST['radio'] or $_GET['radio'] will return an array of all the values which you specify. Notice how the value attribute has been filled in above. Do this for each of the rows.
Also be careful about using my_sql connections. It's depreciated as of PHP 5.5.0. Use mysqli or PDO instead, it's more secure. http://ie1.php.net/function.mysql-connect
Check it this link. it compares and provides examples on both
I don't see where you're connecting the query search and form page, but you could create the link back containing the data in GET params in the url, since I don't see password or private material in these fields. Then use php to populate the forms.
$url = "your_form_page?";
while($row = mysql_fetch_array($query))
{
$url .= "fname=" . $row['FIRSTNAME'];
$url .= "&lname=" . $row['LASTNAME'];
$url .= "&arrival=" . $row['ARRIVAL'];
}
// $url = your_form_page?fname=bob&lname=jones&arrival=blah
Then to populate the form..
<form action="insert_submit.php" method="post">
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" value="<?php echo $_GET['fname']; ?>" />
Hopefully this helps or at least gets you thinking in the right direction.
I have created a song database (mysql) where a user can enter data into the textfield, select "by artist" or a "by title" radio button and click submit. This all works fine. :)
However, I would like to add another submit button that bypasses the above query and simply lists all of the songs that have been added to the database with a year's time.
I believe that the query I need is:
select * from dt_tb where `dt` >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
but I cannot figure out how to code the PHP to run the query for the songs within the past year.
Here are the two forms I have:
<p>
<form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="Submit" value="Search" />
</form></p>
<form name="form" method="post" action="">
<br />
<input type="submit" name="Newsongs" value="New Releases" />
</form></p>
and here is the current, working php for the 1st query:
<?php
$delimiter = "\t";
$newline = "\n";
$var = #$_GET['q'] ;
$field = #$_GET['field'];
$var = htmlentities($var);
$trimmed = trim($var); //trim whitespace from the stored variable
$search_words = explode(' ', $var);
if ($var != "") {
// rows to return
$limit=100;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database
mysql_connect("DBLocation","DatabaseName","PASSWORD"); //(host, username, password)
//specify database
mysql_select_db("DatabaseName") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "SELECT * FROM Songs where $field like \"%$trimmed%\" order by $field ";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";
// begin to show results set
echo "<p style=\"color: #00ff00; font-size: 1.2em;\">Results</p>";
$count = 1 + $s ;
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["title"];
$artist = $row["artist"];
echo "$title";
echo " - ";
echo "$artist";
echo "<br />";
echo $newline;
$count++ ;
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
}
?>
You can add a hidden field and then check it on submit:
<input type="hidden" name="act" id="act" value="">
Then on your second submit button, use JavaScript to change the value:
<input type="submit" name="Newsongs" value="New Releases" onclick="document.getElementById('act').value = 'list_all'" />
If the value is "list_all", process that, else do your current processing.
if ($_POST['act'] == 'list_all') {
// process second submit button code
} else {
// all your current code
}
You'll want to check if the NewSongs submit button was on the form submitted, and use that in an if statement to do the query or not.
<?php
if (!isset($_POST['NewSongs'])){
//do the search
} else {
//don't do the search
}
?>
You could use 2 submit button inside a form :
<p><form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="submit" value="Search" />
<input type="submit" name="submit" value="New" />
</form>
</p>
<?php
if(isset($_GET['submit']) && $_GET['submit'] == 'Search'){
// do search
}
if(isset($_GET['submit']) && $_GET['submit'] == 'New'){
// do second search
}
?>
this is my coding for search box in my database but when i run it it shows the error Notice: Undefined variable: searching in /opt/lampp/htdocs/1234.php on line 15
then i i type anything in my search box
it says
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.3 (Unix) OpenSSL/1.0.1c PHP/5.4.7
<html>
<h2>Search</h2>
<form name="search" method="post" action="<?=$PHP_SELF?>">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="fname">diseasename</option>
<Option VALUE="lname">genename</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
</html>
<?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;
}
// Otherwise we connect to our Database
mysql_connect("localhost", "root", "****") or die(mysql_error());
mysql_select_db("missensencemuttation") 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 users WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['fname'];
echo " ";
echo $result['lname'];
echo "<br>";
echo $result['info'];
echo "<br>";
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 dont know what i did wrong in my script. and i am a beginner in php and i am using internet reference for gaining knowledge in php.can one correct this script
use like below:
extract($_POST);
if ($searching =="yes")
$searching is not defined at this moment in the script. I think you mean $_POST['searching'].
Add an if (isset($_POST['searching'])) { //old if } around the comparison to be sure that $_POST['searching'] is set and replace $searching with $_POST['searching']
EDIT: Replace $PHP_SELF with $_SERVER['PHP_SELF'] , this could help you out.
Please check out this mock up of a search on my site:
LINK EXPIRED
The search doesn't return any results and no error messages are shown, why is this?
I have taken out my person information ie. host/username/password
HTML:
<h2>Search</h2>
<form name="search" method="post" action="<?=$PHP_SELF?>">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="fname">First Name</option>
<Option VALUE="lname">Last Name</option>
<Option VALUE="info">Profile</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
php:
<?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;
}
// Otherwise we connect to our Database
mysql_connect("MYHOST", "MYUSERNAME", "MYPASSWORD") or die(mysql_error());
mysql_select_db("MYDATABSENAME") 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 users WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['fname'];
echo " ";
echo $result['lname'];
echo "<br>";
echo $result['info'];
echo "<br>";
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;
}
?>
Thanks!
Jmames
You are assuming the server is using register_globals, which is a terrible terrible thing. You should do something like if ($_POST['searching'] =="yes") instead. This is probaly also why nothing happens.
The docs says
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
Your code is also extremely vulnerable to SQL injection, which you can fix with mysql_real_escape_string.
Your query should look like this
$data = mysql_query("SELECT * FROM users WHERE upper(".mysql_real_escape_string($field).") LIKE'%".mysql_real_escape_string($find)."%'");
Did you write:
$searching = $_POST['searching'];
Before:
if ($searching =="yes")
?