I have made a HTML search form which creates a query to a MySql database based on the contents of a form. What I would love to do is ignore the search parameter if the user leaves that specific form field empty. There are lots of answers online, especially on this website, but I can't get any of them to work.
I have stripped down my code as much as possible to paste into here:
The HTML input:
<form action="deletesearchresults.php" method="GET">
<p><b>First Part Of Postcode</b>
<input type="text" name="searchpostcode"></b> </p>
<p><b>Category</b>
<input type="text" name="searchfaroukcat"></b>
<input type="submit" value="Search">
</p>
</form>
The PHP results display:
<?php
mysql_connect("myip", "my_username", "my_password") or die("Error connecting to database: ".mysql_error());
mysql_select_db("my_db") or die(mysql_error());
$sql = mysql_query("SELECT * FROM
GoogleBusinessData
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]' LIMIT 0,20");
while($ser = mysql_fetch_array($sql)) {
echo "<p>" . $ser['BusName'] . "</p>";
echo "<p>" . $ser['PostcodePostalTown'] . "</p>";
echo "<p>" . $ser['PostcodeArea'] . "</p>";
echo "<p>" . $ser['FaroukCat'] . "</p>";
echo "<p> --- </p>";
}
?>
This works great until I leave one field blank, in which case it returns no results as it thinks I am asking for results where that field is empty or null, which I don't wat. I want all of the results where that form field is empty.
I tried combining a like % [myfeild] % etc but I only want the results to display exactly what is on the field and not just the ones that contain what is in the field, for example searching for the postcode "TR1" would return results for TR1, TR10, TR11 etc.
I believe I may need an array but after 3 days of trying, I just don't know how to get this done.
Any help would be amazing.
edit: Also, I will be adding up to ten fields to this form eventually and not just the two in this example so please bear this in mind with any suggestions you may have.
try using isset()
example
if(isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]'";
}elseif(isset($_GET[searchpostcode]) && !isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]'";
}elseif(!isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE FaroukCat = '$_GET[searchfaroukcat]'";
}else{
$fields = "";
}
$sql = "SELECT * FROM
GoogleBusinessData $fields
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull LIMIT 0,20";
You do however need to escape your $_GET variables however i would highly recommend using PDO/mysqli prepared statements http://php.net/manual/en/book.pdo.php or http://php.net/manual/en/book.mysqli.php
or try a foreach loop
foreach($_GET as $keys=>$value){
$values .= $keys."='".$value."' and";
}
$values = rtrim($values, " and");
if(trim($values) != "" || trim($values) != NULL){
$query = "WHERE ".$values;
}else{
$values = "";
}
$sql = "SELECT * FROM `test`".$values;
Related
Below is my PHP code which find the result from mysql table what is typed by user search to search field. It is also finds if user has typed something randomly and find the matching row fetch from the database and show to user. But there is one problem it will fetch the record from the databse as they are sequentially store into the database. but i want is it will show the result which matches the most of the keywords or sentence which is type by user. for example user searching for "search and pagination with php" and all the records are fetch from the database
results:
1. PHP RSS Feed Read and List2.DropDown with Search using jQuery 3.PHP CRUD with Search and Pagination 4.PHP MySQL Date Range Search with jQuery DatePicker"
This is how my code is working. But i want is that result 3rd should be came 1st positon beacuse it matches the greater number of keywords matching and others should also came after that because it have some matching keywords. I have also attached the screenshot of same result screenshot.
If we are searching something in google we are search just randomly. everyone searching type is different but topic is same so google will return the exact result even if type in another way or spelling is typed wrong. How can I do that or what are changes I have to make in code. and If I want to add auto suggestions like google then How can I do that. I want a search field which works like google or StackOverflow for finding the result which has similar or matching results in PHP.
<?php
$conn = mysqli_connect("localhost", "root", "", "blog_samples");
$with_any_one_of = "";
$with_the_exact_of = "";
$without = "";
$starts_with = "";
$search_in = "";
$advance_search_submit = "";
$queryCondition = "";
if(!empty($_POST["search"])) {
$advance_search_submit = $_POST["advance_search_submit"];
foreach($_POST["search"] as $k=>$v){
if(!empty($v)) {
$queryCases = array("with_any_one_of","with_the_exact_of","without","starts_with");
if(in_array($k,$queryCases)) {
if(!empty($queryCondition)) {
$queryCondition .= " AND ";
} else {
$queryCondition .= " WHERE ";
}
}
switch($k) {
case "with_any_one_of":
$with_any_one_of = $v;
$wordsAry = explode(" ", $v);
$wordsCount = count($wordsAry);
for($i=0;$i<$wordsCount;$i++) {
if(!empty($_POST["search"]["search_in"])) {
$queryCondition .= $_POST["search"]["search_in"] . " LIKE '%" . $wordsAry[$i] . "%'";
} else {
$queryCondition .= "title LIKE '" . $wordsAry[$i] . "%' OR description LIKE '" . $wordsAry[$i] . "%'";
}
if($i!=$wordsCount-1) {
$queryCondition .= " OR ";
}
}
break;
}
}
}
}
$orderby = " ORDER BY id desc";
$sql = "SELECT * FROM links " . $queryCondition;
$result = mysqli_query($conn,$sql);
?>
<html>
<head>
<title>Advanced Search using PHP</title>
<script>
function showHideAdvanceSearch() {
if(document.getElementById("advanced-search-box").style.display=="none") {
document.getElementById("advanced-search-box").style.display = "block";
document.getElementById("advance_search_submit").value= "1";
} else {
document.getElementById("advanced-search-box").style.display = "none";
document.getElementById("with_the_exact_of").value= "";
document.getElementById("without").value= "";
document.getElementById("starts_with").value= "";
document.getElementById("search_in").value= "";
document.getElementById("advance_search_submit").value= "";
}
}
</script>
</head>
<body>
<h2>Advanced Search using PHP</h2>
<div>
<form name="frmSearch" method="post" action="index.php">
<input type="hidden" id="advance_search_submit" name="advance_search_submit" value="<?php echo $advance_search_submit; ?>">
<div class="search-box">
<label class="search-label">With Any One of the Words:</label>
<div>
<input type="text" name="search[with_any_one_of]" class="demoInputBox" value="<?php echo $with_any_one_of; ?>" />
</div>
<div>
<input type="submit" name="go" class="btnSearch" value="Search">
</div>
</div>
</form>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<div>
<div><strong><?php echo $row["title"]; ?></strong></div>
<div class="result-description"><?php echo $row["description"]; ?></div>
</div>
<?php } ?>
</div>
</body>
</html>
trial 2
You can compare the results of the search the user inputs and the query results before displaying them. Compare how many words are similar for each result from the array and print the one that has the most first.
$advance_search_submit
$wordsAry[$i]
You could easily use both variables to compare how many words in wordsAry are similar to advance_search_submit and store them in a displayResults array in order of which have more words in common.
Or
Could do the same thing but compare it to the title of the results.
$results
$wordsAry[$i]
Comparing these two variables in a similar way to above. Compare words to result (contains) and save them in order in another array to be displayed.
For all those that care, the if not empty statement worked for me
I'm new to SQL and PHP and am trying to implement a search functionality to grab data from a MySQL database that deals with wines.
I have figured out how to do a query where there is one search variable, and I have figured out how to do it with two search variables, i'm sure i could continue on that pattern - but what i'd like to do is implement a search function that can search based on what the user inputs into the variables (That means, the user must enter at least one value, and the search will grab fields relevant to the search variable).
Say for example I have these search variables:
wine name - (user can leave this blank or enter a value)
wine type - (user enters a value)
year - (user can leave this blank or enter a value)
Based on how many variables the user enters will dictate how refined the search is.
I've tried searching the forums but can't seem to find anything. Apologies if my formatting, or question is wrong. Would appreciate any help or a point in the right direction, thanks!
Here is my code so far that works if the user enters both variables 'wineName' and 'wineryName'. Tried using isset to trigger some sort of switch, but i don't think i'm on the right track.
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Answer Page</title>
</head>
<body bgcolor="white">
<?php
function showerror() {
die("Error " . mysql_errno() . " : " . mysql_error());
}
require 'db.php';
// Show all wines in a region in a <table>
function displayWines($connection, $query, $wineName) {
// Run the query on the server
if (!($result = # mysql_query ($query, $connection))) {
showerror();
}
// Find out how many rows are available
$rowsFound = # mysql_num_rows($result);
// If the query has results ...
if ($rowsFound > 0) {
// ... print out a header
print "You searched for $wineName with a region of $wineryName <br><br>";
// and start a <table>.
print "\n<table>\n<tr>" .
"\n\t<th>Wine ID</th>" .
"\n\t<th>Wine Name</th>" .
"\n\t<th>Winery Name</th>" .
"\n\t<th>Year</th>\n</tr>";
// Fetch each of the query rows
while ($row = # mysql_fetch_array($result)) {
// Print one row of results
print "\n<tr>\n\t<td>{$row["wine_id"]}</td>" .
"\n\t<td>{$row["wine_name"]}</td>" .
"\n\t<td>{$row["winery_name"]}</td>" .
"\n\t<td>{$row["year"]}</td>\n</tr>";
} //end while loop body
//finish table
print "\n</table>";
} //end if $rowsFound body
//Report how many rows were found
print "<br>{$rowsFound} records found matching your criteria<br>";
} //end of function
// Connect to the MySQL server
if (!($connection = # mysql_connect(DB_HOST, DB_USER, DB_PW))) {
die("Could not connect");
}
//get user data
$wineName = $_GET['wineName'];
$wineryName = $_GET['wineryName'];
if (!mysql_select_db(DB_NAME, $connection)) {
showerror();
}
//start a query
$query = "SELECT wine_id, wine_name, winery_name, year
FROM wine, winery
WHERE wine.winery_id = winery.winery_id";
if (isset($wineName)) {
$query .= " AND wine_name = '{$wineName}'";
}
if (isset($wineryName)) {
$query .= " AND winery_name = '{$wineryName}'";
}
//order the list
$query .= " ORDER BY wine_name";
//run query, show results
displayWines($connection, $query, $wineName);
?>
</body>
</html>
//start a query
$query = "SELECT wine_id, wine_name, winery_name, year
FROM wine, winery
WHERE wine.winery_id = winery.winery_id";
if (isset($wineName)) {
$query .= " AND wine_name LIKE '%$wineName%'";
}
if (isset($wineryName)) {
$query .= " AND winery_name LIKE '%$wineryName%'";
}
//order the list
$query .= " ORDER BY wine_name";
//run query, show results
displayWines($connection, $query, $wineName);
First of all, change your INPUT's names to an array, e.g.
<input name="wine[wineName]" ...>
<input name="wine[wineryName]" ...>
Now you have to change the way you get the user data:
// Define an array of allowed fields ("whitelist")
$fields = array('wineName', 'wineryName');
// Get the fields given by the user
$wine = array();
foreach($fields as $field)
if (isset($_GET['wine'][$field]))
$wine[$field] = mysql_real_escape_string($_GET['wine'][$field]);
// ... your code here ...
//start a query
$query = "SELECT wine_id, wine_name, winery_name, year
FROM wine, winery
WHERE wine.winery_id = winery.winery_id";
foreach ($wine as $field => $value) $query .= " AND ".$field." = '".$value."'";
One important hint: NEVER use user given input in your query without escaping! (see http://php.net/manual/en/function.mysql-real-escape-string.php)
Please have a look at the following lines:
print "\n<tr>\n\t<td>{$row["wine_id"]}</td>" .
"\n\t<td>{$row["wine_name"]}</td>" .
"\n\t<td>{$row["winery_name"]}</td>" .
"\n\t<td>{$row["year"]}</td>\n</tr>";
It should be
print "\n<tr>\n\t<td>{$row['wine_id']}</td>" .
"\n\t<td>{$row['wine_name']}</td>" .
"\n\t<td>{$row['winery_name']}</td>" .
"\n\t<td>{$row['year']}</td>\n</tr>";
instead. Your double quotes for the array key are closing your string.
Note:
Because your tutor has said to use the deprecated mysql_* functions you can't do much about it. But please bear in mind, that you better should use parameterized prepared statements and bind your input values to the parameters (with PDO or mysqli).
I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";
I want to query the database according to the input of the amount deposited. In the database the bank minimal amounts are stored. So the query consists in showing all banks with min_amount
The amount is defined $amount, and the row containing the minimum amounts is minimum. So i have done it like this but it tells me: Undefined index for $amount. ???
<form name="test" method="get" action="this.php">
Amount: <input name="amount"/>
<input type="submit"/>
</form>
<?php
$amount = $_GET["amount"];
$result = mysql_query("SELECT * FROM list1 WHERE minimum <= '$amount'");
while($row = mysql_fetch_array($result))
{
echo $row['bank_name'] . " - " . $row['Tariff'];
echo "<br />";
}
?>
You need to check if the form has been submitted or not. Try:
if( isset($_GET['amount'])) { /* your code here */ }
You need to check if the form has been submitted with say isset function.
if (isset($_GET['amount'])){}
Also it is highly advisable that you escape your $_GET variables before placing them into a mysql query as this kind of code allows for SQL injections.
The whole thing should like this:
if (isset($_GET['amount'])){
$amount = $_GET["amount"];
$result = mysql_query("SELECT * FROM list1 WHERE minimum <= '{$amount}'");
while($row = mysql_fetch_array($result))
{
echo $row['bank_name'] . " - " . $row['Tariff'];
echo "<br />";
}
There might be an easy answer to this, but I can't for the life of me get this to work.
I'm using PHP and MySQL and have something like this set up:
$studentname = mysql_real_escape_string($_POST['sname']);
$studentnumber = mysql_real_escape_string($_POST['snumber']);
$course = mysql_real_escape_string($_POST['courseselect']);
$bike3 = mysql_query("SELECT stoodnumber FROM bikes505 WHERE stoodname='" . $studentname . "'");
$bikestoods = mysql_fetch_array($bike3);
while($row = mysql_fetch_array($stoodlistq))
{
$stoodentname = $row['stoodname'];
$stoodentnumber = $row['stoodnumber'];
//$coursename = $row2['coursename'];
//$coursecode = $row2['coursecode'];
if($studentname == $stoodentname && $studentnumber == $stoodentnumber){
//$success = 1;
//$success = "yupp";
//echo "SUCCESS, WE CAN REGISTER YOOOU!";
echo "<br>";
//echo "INSERT INTO " . $course . "";
switch($course){
case "Biking Safely":
if($studentnumber = $bikestoods[0] or $bikestoods[1]){
echo "Sorry, this student has already registered";
} else if($bikecurrent < $bikemax){
mysql_query("INSERT INTO bikes505 VALUES ('" . $stoodentname . "','" . $stoodentnumber . "')");
echo "Yay, successfully registered " . $stoodentname . " - " . $stoodentnumber . " for " . $course;
echo "<br>";
} else{
echo "Sorry, class is full!";
}
break;
...and so on. The only problem that I'm having is that if I have two students with the same name, the second in the list will echo that the information is not correct.
For example, the MySQL table has 'stoodname' and 'stoodnumber', and if 'Jimmy St.James','1010' and 'Jimmy St.James','1090' are both records in the table it will only let me enroll Jimmy 1010 in the course and not Jimmy 1090.
Am I just way off with how I'm validating? Or am I missing something really obvious? At first I assumed it was just because I was only using the first item in the array $bikestoods[0] so I changed it to $bikestoods[0] or $bikestoods[1] and it still doesn't work.
Per a comment, you have $stoodlistq defined as:
$stoodlistq = mysql_query("SELECT * FROM stoodinfo");
Later, you use the following block of code:
$studentname = mysql_real_escape_string($_POST['sname']);
$studentnumber = mysql_real_escape_string($_POST['snumber']);
...
while($row = mysql_fetch_array($stoodlistq)) {
...
if($studentname == $stoodentname && $studentnumber == $stoodentnumber){
The while() loop in this code iterates over every record, however, the if-statement checks against the POST variables. The POST variables make up a single combination for "one student" - therefore, you'll only ever get a single student that can be enrolled.
To fix the issue, you'll either need to update your form that submits the "student name"/"student number" to accept multiple inputs - or update the if-statement to only check against the student's name (which could lead to a more undesired situation).
You are doing your query looking for stoodname . When you are doing things like this is not good to do this statements by a value that can be repeated. Maybe you want them to login with a username and password, or maybe with an id that you give to them, but unless somebody here has a better idea, i don't think you will be able to do it by the name.
$bikestoods = mysql_fetch_array($bike3);
only refers to the first result of bike3 query and only has 2 cols : [0] and [stoodnumber] no [1]. If you want to collect all ids that are in bike3, you have to curse the result one time.
while($stoodnumbers[] = mysql_fetch_array($bike3));