I am new to creating a search form, below is my code for the search form:
<h2>Search</h2>
<form name="search" method="post" action="search_result2.php">
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="testA">A</option>
<Option VALUE="testB">B</option>
<Option VALUE="testC">C</option>
<Option VALUE="testD">D</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
UPDATED: search_result2.php:
<?php
//This is only displayed if they have submitted the form
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("host", "username", "passw") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($_POST['find']);
$find = strip_tags($_POST['find']);
$find = trim ($_POST['find']);
$field = trim ($_POST['field'])
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM testtable WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['testA'];
echo " ";
echo $result['testB'];
echo "<br>";
echo $result['testC'];
echo "<br>";
echo $result['testD'];
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;
}
?>
==========================
now what is happening is whether I put in a search string or not it will display the following messages, which is exactly my code for the search result,
Results:
"; //If they did not enter a search term we give them an error if ($find == "") { echo "
You forgot to enter a search term";
exit;
} // Otherwise we connect to our Database
mysql_connect("host", "username", "passw") or die(mysql_error());
mysql_select_db("testdb") 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 testtable WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data )) {
echo $result['testA'];
echo " ";
echo $result['testB'];
echo " ";
echo $result['testC'];
echo " ";
echo $result['testD'];
echo " ";
echo " ";
} //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
"; } //And we remind them what they searched for echo "Searched For: " .$find; } ?>
Indeed use <?phpinstead of <?
few other recommendations
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "<p>You forgot to enter a search term";
exit;
}
also suggest you strip tags on $field
don't use <? insted of use <?php short_open_tag can be disabled at server.
Related
I am trying to create a drop-down list to display vehicles that are on "special" on my web browser that are from my database. I would like them to display in price order of asc to desc. I have the coding of the list but for some reason when you click on the display results it doesn't work. What am I missing?
<form method="post" action='<?php echo $_SERVER['PHP_SELF']; ?>' >
<select name="sort">
<option value="ASC">Ascending</option>
<option value="DESC">Descending</option>
</select>
<input type="submit" name="update" value= "Display results">
</form>
<?php
// set initial value for variables to avoid errors the first time the page runs
$sort_name = "ASC";
$price="price";
// check to see if the form value has been set and if so return the value
if(isset($_POST['sort'])) {
// set the variable to the value selected from the dropdown - either ASC or DESC
$sort_name = $_POST['sort'];
}
// create the query inserting the value for the sort order with the variable $sort_name
$query = "SELECT * FROM vehicle WHERE special='yes'ORDER BY $price ASC";
$results = mysqli_query($conn, $query );
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
}
else {
// fetch and display results
while ($row = mysqli_fetch_array($results)) {
echo "<p>VIN_#: $row[vin]</p> ";
echo "<p>Stock Number: $row[stockno]</p> ";
echo "<p>Manufacturer Number: $row[man_num]</p>";
echo "<p>Model: $row[model]</p>";
echo "<p>Colour: $row[col_id]</p>";
echo "<p>Year: $row[year]</p>";
echo "<p>Price: $row[price]</p>";
echo "<p>Kilometres: $row[kms] </p>";
echo "<p>Registration: $row[rego] </p>";
echo "<p>Cylinders: $row[cylinders] </p>";
echo "<p>Fuel: $row[fuel] </p>";
echo "<p>Transmission: $row[transmission] </p>";
echo "<p>Category Id: $row[cat_id] </p>";
echo "<p>Vehicle on Special (yes/no): $row[special] </p>";
echo "<p>Standard Used Vehicle: $row[standardusedvehicle] </p>";
echo '<img src="'.$row[vehicle_image] . "\" >";
}
}
$query = "SELECT * FROM vehicle WHERE special='yes'ORDER BY $price ASC";
$results = mysqli_query($conn, $query );
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
}
else {
// fetch and display results
while ($row = mysqli_fetch_array($results)) {
echo "<p>VIN_#: $row[vin]</p> ";
echo "<p>Stock Number: $row[stockno]</p> ";
echo "<p>Manufacturer Number: $row[man_num]</p>";
echo "<p>Model: $row[model]</p>";
echo "<p>Colour: $row[col_id]</p>";
echo "<p>Year: $row[year]</p>";
echo "<p>Price: $row[price]</p>";
echo "<p>Kilometres: $row[kms] </p>";
echo "<p>Registration: $row[rego] </p>";
echo "<p>Cylinders: $row[cylinders] </p>";
echo "<p>Fuel: $row[fuel] </p>";
echo "<p>Transmission: $row[transmission] </p>";
echo "<p>Category Id: $row[cat_id] </p>";
echo "<p>Vehicle on Special (yes/no): $row[special] </p>";
echo "<p>Standard Used Vehicle: $row[standardusedvehicle] </p>";
echo '<img src="'.$row[vehicle_image] . "\" >";
}
}
?>
I have connected to my database earlier in my coding
Any Ideas would be great
The sql statement is currently sorting ASC and is rigidly typed, try instead to use the value that is sent by the form submission
$sql="SELECT * FROM vehicle WHERE special='yes'ORDER BY {$price} {$_POST['sort']}";
The code is however vulnerable to sql injection so you would be better looking at using prepared statements
The code you posted had a few errors - each field in the html output needs to be quoted otherwise PHP will assume you are using constants and will throw an error. The image was not correctly using single and double quotes.
<form method="post" action='<?php echo $_SERVER['PHP_SELF']; ?>' >
<select name="sort">
<option value="ASC">Ascending</option>
<option value="DESC">Descending</option>
</select>
<input type="submit" name="update" value= "Display results">
</form>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$sort_name = isset( $_POST['sort'] ) && in_array( strtolower( $_POST['sort'] ), array( 'asc','desc' ) ) ? $_POST['sort'] : 'ASC';
$price="price";
$query = "SELECT * FROM vehicle WHERE special='yes' ORDER BY {$price} {$sort_name}";
$results = mysqli_query($conn, $query );
if( !$results ) {
echo ("Query error: ");
} else {
/*
The fields must be quoted otherwise they will be treated as constants, most likely undefined
*/
while ($row = mysqli_fetch_array($results)) {
echo "
<p>VIN_#: {$row['vin']}</p>
<p>Stock Number: {$row['stockno']}</p>
<p>Manufacturer Number: {$row['man_num']}</p>
<p>Model: {$row['model']}</p>
<p>Colour: {$row['col_id']}</p>
<p>Year: {$row['year']}</p>
<p>Price: {$row['price']}</p>
<p>Kilometres: {$row['kms']}</p>
<p>Registration: {$row['rego']}</p>
<p>Cylinders: {$row['cylinders']}</p>
<p>Fuel: {$row['fuel']}</p>
<p>Transmission: {$row['transmission']}</p>
<p>Category Id: {$row['cat_id']}</p>
<p>Vehicle on Special (yes/no): {$row['special']}</p>
<p>Standard Used Vehicle: {$row['standardusedvehicle']}</p>
<img src='{$row['vehicle_image']}' />";/* The image was not correctly set using single quotes */
}
}
}
?>
If you are going to use PHP_SELF as the form action ( or at all in your code ) you really ought to try to make it safe from XSS attacks - or use $_SERVER['SCRIPT_NAME'] instead. That said, try using:
<?php
$action = htmlspecialchars( $_SERVER['PHP_SELF'], ENT_QUOTES, 'utf-8');
?>
<form method="post" action='<?php echo action; ?>' >
I have a database created with five fields
ValueA
ValueB
ValueC
ValueD
ValueE
and I am trying to make a search form that can search by each of these individual fields, e.g if the value in ValueB was "Blue", select ValueB from the dropdown then type in "Blue" to print out all the values in the row that Blue was a part of. So far, I've created an html file called "findme.html":
<html>
<head>
<title>Search</title>
</head>
<body bgcolor=#ffffff>
<h2>Search</h2>
<form name="search" method="post" action="findme2.php">
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="ValueA">Value A</option>
<Option VALUE="ValueB">Value B</option>
<Option VALUE="ValueC">Value C</option>
<Option VALUE="ValueD">Value D</option>
<Option VALUE="ValueE">Value E</option>
</Select>
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
and also created a php file called "findme2.php":
<html>
<head>
<title>Searching through Database Table mytablename</title>
</head>
<body bgcolor=#ffffff>
<?php
include "config.php";
echo "<h2>Search Results:</h2><p>";
if(isset($_POST['search']))
{
$find =$_POST['find'];
}
//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
$username="xxxxxxxx";
$password="xxxxxxxx";
$database="xxxxxx_xxxxxxx";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// We perform 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
$iname = mysql_query("SELECT * FROM mytablename WHERE upper($field) LIKE '%$find%'")
or die(mysql_error());
//And we display the results
while($result = mysql_fetch_array( $iname ))
{
echo "id :" .$result['ValueA'];
echo "<br> ";
echo "name :".$result['ValueB'];
echo "<br>";
echo "name :".$result['ValueC'];
echo "<br>";
echo "name :".$result['ValueD'];
echo "<br>";
echo "name :".$result['ValueE'];
echo "<br>";
echo "<br>";
}
$anymatches = mysql_num_rows($iname);
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;
?>
</body>
</html>
I believe my problem is with the query command, but I am not sure how to adjust the syntax. Can anyone help me?
You forgot to set your $field variable.
In your if statement, you should change it to
if(isset($_POST['search']))
{
$find =$_POST['find'];
$field =$_POST['field'];
}
It should work then.
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.
Can someone have a look at my code Ive finally got working after 2 days and lots of help from here - thank you!
There are a few tweaks i would like to do on it -
for the transaction ID, if i search for any letter in the transaction id, i am shown records - I only want it to show me a record if the FULL transaction ID has been entered and matches the record in the database. Transaction id example: 87K07228GD157974M
if you want to retrieve your code, you must type in your name, email and transaction date, this works perfect BUT the time is also included with the date but i don't want anyone to have to enter the time as well ONLY the date i.e.....
you currently have to enter: 2013-03-07 01:39:23 - but i want to enter in the format of DD/MM/YY - is this possible?
I also don't know if the code is secure also, any advice would be appreciated.
Thanks,
here is the code:
findme.html
<html>
<head>
<title>Search</title>
</head>
<body bgcolor=#ffffff>
<h2>Search Transaction ID</h2>
<form name="search" method="post" action="findme.php">
Seach for: <input type="text" name="find" />
<input type="submit" name="search" value="Search" />
</form>
OR
<h2>Search Name, E-Mail & Transaction Date</h2>
<form name="search" method="post" action="findme1.php">
Full Name (on paypal account) <input type="text" name="name" /> <br><br>
Paypal E-Mail Address <input type="text" name="email" /> <br><br>
Transaction Date - DD/MM/YY <input type="text" name="date" />
<input type="submit" name="search" value="Search" /><br><br>
If searching via Name, E-Mail & Transaction date, all fields must be completed to obtain your code.
</form>
</body>
</html>
findme.php
<html>
<head><title>Searching for a student...</title>
</head>
<body bgcolor=#ffffff>
<?php
echo "<h2>Search 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("location.com", "ipn", "password!") or die(mysql_error());
mysql_select_db("ipn") or die(mysql_error());
// We perform 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
$iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id LIKE '%$find%'");
//And we display the results
while($result = mysql_fetch_array( $iname ))
{
echo "<b>Name: </b>";
echo $result['iname'];
echo " ";
echo "<br>";
echo "<b>E-mail: </b>";
echo $result['iemail'];
echo "<br>";
echo "<b>Transaction Date: </b>";
echo $result['itransaction_date'];
echo "<br>";
//And we remind them what they searched for
echo "<b>Search Term </b>(Transaction ID): </b> " .$find;
//}
echo "<br>";
echo "<br>";
echo "<b>Login Code: </b>";
echo $result['ipaymentstatus'];
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($iname);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your search, please make sure the correct details have been entered...<br><br>";
}
?>
</body>
</html>
findme1.php
<html>
<head><title>Searching for a student...</title>
</head>
<body bgcolor=#ffffff>
<?php
echo "<h2>Search Results:</h2><p>";
//If they did not enter a search term we give them an error
if ($name == "")
if ($email == "")
{
echo "<p>Please enter Full Name, E-Mail Address & Transaction Date EXACTLY how they appear on your PayPal Account...";
exit;
}
// Otherwise we connect to our Database
mysql_connect("location.com", "ipn", "password") or die(mysql_error());
mysql_select_db("ipn") or die(mysql_error());
// We perform 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
$name = mysql_query("SELECT * FROM ibn_table WHERE iemail = '$email' AND iname = '$name' AND itransaction_date = '$date'");
//And we display the results
while($result = mysql_fetch_array( $name ))
{
echo "<b>Name: </b>";
echo $result['iname'];
echo " ";
echo "<br>";
echo "<b>E-mail: </b>";
echo $result['iemail'];
echo "<br>";
echo "<b>Transaction Date: </b>";
echo $result['itransaction_date'];
echo "<br>";
//And we remind them what they searched for
echo "<b>Search Term </b>(Transaction ID): " .$name;
//}
echo "<br>";
echo "<br>";
echo "<b>Login Code: </b>";
echo $result['ipaymentstatus'];
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($name);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your search, please make sure the correct details have been entered...<br><br>";
}
?>
</body>
</html>
Fields in my database are:
iname
iemail
itransaction_id
ipaymentstatus
itransaction_date
Thanks!
As stated in comment for transaction ID you have :
$iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id LIKE '%$find%'");
what LIKE with %$find% does is match any part from transaction ID with $find that is why you get results with single letter. Change that to :
$iname = mysql_query("SELECT * FROM ibn_table WHERE itransaction_id = '$find'");
for date issue you can decide what to take from user like you stated date then for example :
if you take :
$date = "12-11-2012"; //(dd-mm-yyyy)
$split = explode("-", $date);
then you can use this to generate SQL date/time format :
$sql_date = date("Y-m-d h:i:s", mktime(0, 0, 0, (int) $split[1], (int) $split[0], (int) $split[2]))
and in sql query :
transaction_date LIKE '$sql_date%'
And at last don't use mysql_* it is deprecated. Instead use mysqli.
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")
?