PHP Search bar does not display data - php

I must have a problem somewhere with formatting my code but cant find where,
This is the form I place the search bar in:
<form>
<?php include_once("searchbar.php"); ?>
</form>
This is my search bar code:
<form method= "post" action = "search.php">
<input type="text" name="search_input" placeholder="Search Designer Sofas..." />
<input type="submit" value="Search" />
</form>
And this is the beginning of the search results page
<!DOCTYPE html>
<?php
//retrieves the specified element from the URL
$search_input = $_POST["search_input"];
include_once("connection_to_db.php");
//isset function checks if a variable is set
if(!isset($search_input))
{
print("Nothing to search !");
return;
}
//take the books with the specific name
$query_products = "SELECT * FROM XXX WHERE name LIKE '%".$search_input."%'";
$query_product_result = mysql_query($query_products)
or die(mysql_error());
$num_rows_products = mysql_num_rows($query_product_result);
?>
<html lang="en">
<head>
Now what happens is that when I click on the search button the address changes in the url to the search query but the page doesnt, does it mean that it is sending to it but not receiving anything?

It looks like you have nested <form> elements. This is how your form is rendering:
<form>
<form method= "post" action = "search.php">
<input type="text" name="search_input" placeholder="Search Designer Sofas..." />
<input type="submit" value="Search" />
</form>
</form>
The second form (the one with the action) will be ignored. Remove the <form> wrapper where you include searchbar.php.
You're also wide open to SQL injection attacks. Consider using mysqli prepared statements.

enter = sign for action
<form method="post" action="search.php">
<input type="text" name="search_input" placeholder="Search Designer Sofas..." />
<input type="submit" value="Search" />
</form>
and try to remove form tags from
<?php include_once("searchbar.php"); ?>

Related

Can't get form value with PHP

I am trying to get the value of a form (text field) with _POST, and store it to a text file but it doesn't work. Here's my code:
HTML
<form>
<input type="text" name="test" id="test" value="">
<input type="button" onclick="location.href='example.com/index.php?address=true';" value="ODOSLAŤ" />
</form>
PHP
if (isset($_GET['address'])) {
$email = $_POST['test'];
$myfile = fopen("log.txt","a") or die("Error.");
fwrite($myfile, "\n".$email);
// this prints nothing
echo $email;
}
I can't get the value of that text field. Nor GET nor POST doesn't work for me. What am I doing wrong?
You are missing a post method in your form.
<form method="post" action="example.com/index.php?address=true">
<input type="text" name="test" id="test" value="">
<input type="submit" value="ODOSLAŤ" />
</form>
You also have to change the following line.
if (isset($_GET['address'])) {
With
if (isset($_POST['address'])) {
You want to post after triggering an action as FreedomPride mentioned
Conclusion
You want to declare for example a post methodif you know that you would like to post that data in the future.
As FreedomPride also mentioned :
You are using a GET, but if a user does not input anything your script won't work, there by it is recommended to use a POST
You are not submitting your form.
Change your code as follows....
<form method="post" action="example.com/index.php?address=true">
<input type="text" name="test" id="test" value="">
<input type="submit" value="ODOSLAŤ" />
</form>
You'll get what you want....
This is what you're missing as Tomm mentioned.
<form method="post" action="yourphp.php">
<input type="text" name="address" id="test" value="">
<input type="submit" name="submit"/>
</form>
In your PHP, it should be post if it was triggered
if (isset($_POST['address'])) {
$email = $_POST['test'];
$myfile = fopen("log.txt","a") or die("Error.");
fwrite($myfile, "\n".$email);
// this prints nothing
echo $email;
}
Explanation :-
In a form, an action is required to pass the action to the next caller with action. The action could be empty or pass it's value to another script.
In your PHP you're actually using a GET. What if the user didn't input anything. That's why it's recommended to use POST .

Get Search keyword in URL

<form action="">
<input placeholder="SEARCH" name="search_input" type="text"/>
<input type="submit" name="search_submit"/>
</form>
If people search by "Keyword Item" I want URL will be http://mydomain.com/search?keywords=Keyword%20Item
How can I do it? I know needs configure in form action, get etc.
Thanks in advance.
Update
When I am trying with this code
<form action="http://search.golfoutletsusa.com/search?" method="get">
<input placeholder="SEARCH" name="Keywords" type="text"/>
<input type="submit" name="search_submit"/>
</form>
The URL is: http://search.golfoutletsusa.com/search?Keywords=85&search_submit=Submit+Query
I just want "&search_submit=Submit+Query" will be removed from URL.
<?php echo $_GET["keywords"]; ?>
You will need to change the name of the text field from search_input to keywords though.
You should also consider using an id attribute along with the name. And as the other answer says, form action and method should be set correctly.
Solution:1
You can add the following code at the top of your search.php (or, whatever the processor file):
<?php
if(isset($_GET["search_submit"]))
{
$keywords = $_GET["Keywords"];
header("Location: search.php?Keywords=$keywords");
}
?>
OR
Solution:2
You can omit the name of submit button if it is not really necessary to give it a name. So instead of
<input type="submit" name="search_submit"/>
just use
<input type="submit" />
Set action of the form to search.php and method to get.
Then change the name of your input element to keywords.
But still the url won't be - http://mydomain.com/search?keywords=Keyword%20Item
It will be - http://mydomain.com/search.php?keywords=Keyword%20Item
Simply put everything in the form properties, only you have to select a file which will receive all this, /search will not suffice:
<form action="search.php" method="get">
<input type="text" name="keywords" placeholder="SEARCH" />
<input type="submit" name="submit" />
</form>
EDIT: In the search.php file you would get the variable contents with the get global variable like this:
$search_query = $_GET['keywords'];
After that you simply write the rest of the code to do the search... Note that this would lead to an URL like http://www.example.com/search.php?keywords=query

Auto fill a text box with database information without leaving a page

I have several forms on a page and they have to be filled in automatically by accessing a users ID and then filling the rest of the text boxes with the necessary information. Essentially an auto fill for the forms dependent on which RFID is entered into the first text box.
<html>
<head>
<?php
$con = mssql_connect("123", "abc", "pass");
if (!$con)
{
die('Could not connect: ' . mssql_get_last_message());
}
mssql_select_db("db1", $con);
$result = mssql_query("SELECT * FROM Scrabble");
$row = array("RFID" => "", "Tile" => "", "TileScore" => "");
$row = mssql_fetch_row($result)
?>
</head>
<body>
<form>
<input type="text" name="RFID1"/>
<input type="text" name="Tile1"/>
<input type="text" name="TileScore1"/>
<input type ="button" value="submit" onclick="RFID1.disabled=true" />
<td><input type="text" name="RFID2"/>
<input type="text" name="Tile2"/>
<input type="text" name="TileScore2"/>
<input type ="button" value="submit" onclick="RFID2.disabled=true" />
<input type="text" name="RFID3"/>
<input type="text" name="Tile3"/>
<input type="text" name="TileScore3"/>
<input type ="button" value="submit" onclick="RFID3.disabled=true" />
<form>
</body>
</html>
I need it to take the Tile and TileScore from where the RFID is equal to what is entered in the text box. Is this possible without having to submit the page to allow the other forms to be filled in as well? I've been told it may be possible using AJAX but am unaware of a solution.
This is using MSSQL, sadly there isn't an MSSQL tag.
Disclaimer
I'm assuming that the way you want your page to function is that the user types into the RFID text-field.
To make the code simpler and more flexible I've changed the three form-like segments into three separate forms. This also has an added advantage that if the browser doesn't support JavaScript the page falls back to submitting the form.
I could not make sense of the SQL so I have merely commented it out.
I have also added some extra PHP throughout the page, so that in case of javascript not being available the submitted page will still respond with the form correctly.
To add in your SQL query code, just make sure the resulting Tile and TileScore are placed in variables $tile and $tileScore respectively.
Code
<?php
/*
function sqlStuff(){
$con = mssql_connect('123', 'abc', 'pass');
if(!$con){die('Could not connect: ' . mssql_get_last_message());}
mssql_select_db('db1', $con);
$result = mssql_query('SELECT * FROM Scrabble');
// Why is the following here?
$row = array('RFID' => '', 'Tile' => '', 'TileScore' => '');
$row = mssql_fetch_row($result)
}
*/
$rfid=$_GET['RFID'];
$tile='Tile for "'.$rfid.'"';
$tileScore='TileScore for "'.$rfid.'"';
$separ='/'; //separator
// if this is an ajax request do the following, if not print the page as normal
if($_GET['r']=='ajax'){
$ajaxString=$separ.$tile;
$ajaxString.=$separ.$tileScore;
echo $ajaxString;
}else{
// which form was submitted, only used if form was submitted by browser.
$form=$_GET['form'];
// escape quote characters
$rfid=htmlentities($rfid);
$tile=htmlentities($tile);
$tileScore=htmlentities($tileScore);
?><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>live-submitting form using javascript!</title>
<style type="text/css">
/*<![CDATA[*/
body{font:80% sans-serif;}
/*]]>*/
</style>
<script type="text/javascript">
//<![CDATA[
window.onload=load;
function load(){
document.getElementById('form1').onsubmit=function(){if(submitWithJS(this)){return false;}};
document.getElementById('form2').onsubmit=function(){if(submitWithJS(this)){return false;}};
document.getElementById('form3').onsubmit=function(){if(submitWithJS(this)){return false;}};
}
function submitWithJS(thisForm){
// setup ajax object
var httpReq;
if(window.XMLHttpRequest){// Non-IE
httpReq=new XMLHttpRequest();
}else if(window.ActiveXObject){ // IE
try{httpReq=new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){
try{httpReq=new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){
return false; // some other IE check?
}
}
}else{
return false; // submit without ajax
}
// Actual code:
httpReq.onreadystatechange=function(){
// basically readyState 4 is when reply is recieved
if(this.readyState==4){responder(this,thisForm);}
}
// prepare args
//beware "arguments" is a keyword
var args="?r=ajax"; // type of request
args+="&RFID="+thisForm.RFID.value;
// begin request
httpReq.open("GET",args);
httpReq.send();
return true;
}
function responder(httpResponse,form){
// use the $separ variable from PHP
<?php echo ' var separator="'.$separ.'";'."\n";?>
if(httpResponse.responseText[0]==separator){
var returned=httpResponse.responseText.split(separator); // separation
form.Tile.value=returned[1];
form.TileScore.value=returned[2];
}else{form.submit();}
}
//]]>
</script>
</head>
<body>
<p class="notice">javascript required to use more than one form</p>
<form method="get" action="" id="form1">
<div>
<input type="hidden" name="form" value="1"/>
<input type="text" name="RFID"<?php if($form==1){echo ' value="'.$rfid.'"';}?>/>
<input type="text" readonly="readonly" name="Tile"<?php if($form==1){echo ' value="'.$tile.'"';}?>/>
<input type="text" readonly="readonly" name="TileScore"<?php if($form==1){echo ' value="'.$tileScore.'"';}?>/>
<input type ="submit" value="submit"/>
</div>
</form>
<form method="get" action="" id="form2">
<div>
<input type="hidden" name="form" value="2"/>
<input type="text" name="RFID"<?php if($form==2){echo ' value="'.$rfid.'"';}?>/>
<input type="text" readonly="readonly" name="Tile"<?php if($form==2){echo ' value="'.$tile.'"';}?>/>
<input type="text" readonly="readonly" name="TileScore"<?php if($form==2){echo ' value="'.$tileScore.'"';}?>/>
<input type ="submit" value="submit"/>
</div>
</form>
<form method="get" action="" id="form3">
<div>
<input type="hidden" name="form" value="3"/>
<input type="text" name="RFID"<?php if($form==3){echo ' value="'.$rfid.'"';}?>/>
<input type="text" readonly="readonly" name="Tile"<?php if($form==3){echo ' value="'.$tile.'"';}?>/>
<input type="text" readonly="readonly" name="TileScore"<?php if($form==3){echo ' value="'.$tileScore.'"';}?>/>
<input type ="submit" value="submit"/>
</div>
</form>
</body>
</html>
<?php }?>
Since you're trying to fill text fields on the page based on the input of another text field on the page, you need AJAX or to dump all possibilities of the text fields into javascript variables on the page from PHP (ew).
http://api.jquery.com/jQuery.ajax/
Have it call a PHP script that returns a JSON object that holds the field data based on the RFID text field.

Form Submit - Prevalidation throws IE off

Background: The website I am working on has a search bar at the top. The user inputs a part code for a product and the website returns information about that product.
So, I have a basic search bar that posts parameters from a HTML form into a PHP script, which then does a lookup on a MySQL server to get the Product.
The problem is because some part codes have "#" characters, I have to use Javascript to insert escape characters, otherwise I only get some of the part code in the PHP script.
Example - 123#ABC would be read as 123.
I use a hidden value in the form, which is populated with the Text Box value, modified by the escape() function in Javascript.
This is my code currently, it works in every browser except for IE.
Any help would be much appreciated :)
<script language="jscript">
function changeTextBox()
{
hiddenSearch.value = escape(txtSearch.value);
formSearch.submit;
}
</script>
<form id="formSearch" name="Search" action="?page=search" method="post">
Search by <u>Part Code</u> or <u>Description</u>
<input id="txtSearch" type="text" size="35">
<input id="hiddenSearch" name="Search" type="hidden">
<input name="Submit" onclick='jscript:changeTextBox();' type="submit" value="Submit">
</form>
take a look at changes-- i think there were issues with your javascript.
<script language="jscript">
function changeTextBox()
{
document.getElementById("hiddenSearch").value = escape(document.getElementById("txtSearch").value);
this.submit();
}
</script>
<form id="formSearch" name="Search" action="?page=search" method="post" onsubmit='changeText()'>
Search by <u>Part Code</u> or <u>Description</u>
<input id="txtSearch" type="text" size="35">
<input id="hiddenSearch" name="Search" type="hidden">
<input name="Submit" type="submit" value="Submit">
</form>

How to capture a form element and use dynamically in the post url?

I'm trying to build a form which submits a URL which contains a lon/lat that has been passed over from Google Maps. I have managed to get it so the lon/lat is passed into input fields in the form, how would I go about using these values dynamically in the post URL, i.e.:
action="search.asp?[lon][lat]
If you want to get the values from the form into the URL, set the method attribute to get:
<form method="search.asp" action="get">
. This will put the values of the lon and lat fields of the form in the URL. Example:
search.asp?lat=[lat value]&lon=[lon value]
For more information, read this page. Excerpt:
If the processing of a form is
idempotent (i.e. it has no lasting
observable effect on the state of the
world), then the form method should be
GET. Many database searches have no
visible side-effects and make ideal
applications of query forms.
Using javascript you can change the action attribute of the form. So, create a form..
<form name="myForm">
<input type="hidden" name="lon" value="123" />
<input type="hidden" name="lat" value="321" />
...
<button onclick="setAction();">Submit</button>
</form>
Then in the head of the page add the setAction function..
<script type="text/javascript">
function setAction()
{
var lon = document.myForm.lon.value;
var lat = document.myForm.lat.value;
document.myForm.action = "search.php?["+lat+"]["+lon+"]"';
document.myForm.submit();
}
</script>
Hope this helps, it's how I have done this in the past!
Try using:
<form action="search.php" method="get">
<input type="hidden" name="lon" value="<?php echo $lon_fromGoogleMaps; ?>" />
<input type="hidden" name="lat" value="<?php echo $lat_fromGoogleMaps; ?>" />
<!-- The Rest of your Form... -->
<input type="submit" value="Submit!" />
</form>
Or if you want to use the form as post:
<form action="search.php?lon=<?php echo $lon_fromGoogleMaps; ?>&lat=<?php echo $lat_fromGoogleMaps; ?>" method="post">
<!-- The Rest of your Form... -->
<input type="submit" value="Submit!" />
</form>
I see you tagged this as Javascript as well, and as Google Maps relies heavily on Javascript, you may have the Lon and the Lat passed as Javascript variables...
<script type="text/javascript">
// Obviously, execute this code after the DOM has loaded...
var formAction = document.searchForm.action;
formAction = formAction + '?lon=' + lon_fromGoogleMaps + '&lat=' + lat_fromGoogleMaps;
document.searchForm.action = formAction;
</script>
<form action="search.php" method="post" name="searchForm">
<!-- The Rest of your Form... -->
<input type="submit" value="Submit!" />
</form>

Categories