Search MySQL database via HTML form through PHP - php

I've been struggling for a while, trying to figure out how to connect the following query with the HTML search form.
Query:
<?php
include_once("mysqli_connection.php");
// startpage
$page = 0;
//items pr page
$per_page= 8;
//smileyscore
$smiley_score='';
// perform database query
$query = "SELECT * ";
$query .="FROM smile AS a, smiley_detail AS b ";
$query .= "WHERE a.smiley_id = b.smiley_id AND b.smiley >= 1 ";
$query .= "ORDER BY b.date ";
$query .= "LIMIT ". $page.', '. $per_page . ";";
$result = mysqli_query($connnetion, $query);
$row = mysqli_fetch_row($result);
$rows = $row[0];
if (!$result){
die("database query failed.");
}
?>
Form:
<div class="row">
<div class="col-xs-12">
<form class="menu" action="<?=$PHP_SELF?>" id="searchfor" method="post">
<select type="value" name="smiley_score" placeholder="s">
<option value="0">Alle stikprøver (0)</option>
<option value="1">Ingen anmærkninger (1)</option>
<option value="2">Indskærpelse (2)</option>
<option value="3">Påbud eller forbud (3)</option>
<option value="4">Bødeforlæg, politianmeldelse, autorisation eller registrering frataget (4)</option>
</select>
<select type="text" name="city">
<option value="">By</option>
<option value="København">København</option>
<option value="Århus">Århus</option>
<option value="Odense">Odense</option>
<option value="Alle de andre">Alle de andre</option>
</select>
<select type="value" name="year">
<option value="">År</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
</select>
<input type="text" name="searchcriteria" class="form-control" placeholder="Indtast søgekriterier"> </input>
<button class="btn" id="submit_button" type="submit" name="submit" value="Submit"> Søg</button>
</form>
</div>
</div>
Echo:
<div class="container">
<div class="row">
<?php
while($row = mysqli_fetch_assoc($result)){
// output data from each row
echo '<div class="col-md-12">';
echo '<div class="overskrift">';
echo '<h3>';
echo $row["organisation"] . "<br/>";
echo '</h3>';
echo 'Branche: '.$row["type"] . " - ";
echo 'Dato: '. $row["date"] . " <br /> ";
echo '</div >';
echo '<p class="adress">';
echo $row["adresse1"] . "<br /> ";
echo $row["zip"] . " ";
echo $row["postby"] . " ";
echo '<img class="score" src="img/'.$row["smiley"] .'.gif">';
echo '</p> ';
echo '<div class="textfield" >';
echo $row["text"] . "<br />";
echo '</div>';
echo '</div>';
}
// release data
mysqli_free_result($result);
?>
</div>

There are a few ways you could do this. On the page containing the form a pseudo structure like the following might be the answer.
<html>
<head><title>Searches and results....</title><head>
<body>
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' ){
/* Display the form here */
} elseif( $_SERVER['REQUEST_METHOD']=='POST' ) {
/* Construct and run the sql query */
/* Display the results here */
} else {
/* Wrong method - warn user or redirect or whatever */
}
?>
</body>
</html>

You need process the data, you can get the data on the submited form by adding logic that uses the $_POST associative array to your $PHP_SELF, the name of the form element is what is used in array.
For example if you have an element named data, the PHP to access it would be $_POST['data'].

Make a condition in array form. Change the method as get method .
Customize your query like this
$sql = mysql_query("SELECT * FROM smile WHERE smiley_id LIKE '%$_GET[term]%' LIMIT $page,$_GET[results]");

Related

Performing AJAX search on mysql database using dropdown menus and text input

I work for a group of realtors that have tasked me with designing a property search for their website. I acquired the proper credentials to an IDX feed to grab property information that I then import into my MySQL database and am having trouble grabing specific columns based on the search query. I have only been able to return all fields instead of the ones specified in the search. I have limited knowledge about php, MySQL, mysqli, pdo, ajax, etc. and eventhough the code I am providing is based on AJAX, I am open to any solution that works. Obviously, I am a new user/coder and am happy to add anything I forgot to add. Thank you for taking the time to help me with this problem. I included the html and the separate php file
<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form id="fs_quicksearch" name="fs_quicksearch">
<div class="form-container">
<div class="form-row form-row-loc">
<div class="form-left2">
<label>Location:</label>
</div>
<div class="form-right">
<select class="dd-form-long" id="City"
name="City" onchange="showUser(this.value)">
<option value="">
Any City
</option>
<option value="Auburn">
Auburn
</option>
<option value="Baldwin City">
Baldwin City
</option>
<option value="Basehor">
Basehor
</option>
<option value="Berryton">
Berryton
</option>
<option value="Bonner Springs">
Bonner Springs
</option>
<option value="Carbondale">
Carbondale
</option>
<option value="DeSoto">
DeSoto
</option>
<option value="Effingham">
Effingham
</option>
<option value="Eudora">
Eudora
</option>
<option value="Kansas City">
Kansas City
</option>
<option value="Kanwaka Twp">
Kanwaka Twp
</option>
<option value="Lawrence">
Lawrence
</option>
<option value="Leavenworth">
Leavenworth
</option>
<option value="Lecompton">
Lecompton
</option>
<option value="Lenexa">
Lenexa
</option>
<option value="Linwood">
Linwood
</option>
<option value="Louisburg">
Louisburg
</option>
<option value="McLouth">
McLouth
</option>
<option value="Meriden">
Meriden
</option>
<option value="Nortonville">
Nortonville
</option>
<option value="Osage City">
Osage City
</option>
<option value="Oskaloosa">
Oskaloosa
</option>
<option value="Ottawa">
Ottawa
</option>
<option value="Overbrook">
Overbrook
</option>
<option value="Overland Park">
Overland Park
</option>
<option value="Ozawkie">
Ozawkie
</option>
<option value="Paola">
Paola
</option>
<option value="Parker">
Parker
</option>
<option value="Perry">
Perry
</option>
<option value="Pomona">
Pomona
</option>
<option value="Shawnee">
Shawnee
</option>
<option value="Tecumseh">
Tecumseh
</option>
<option value="Tonganoxie">
Tonganoxie
</option>
<option value="Topeka">
Topeka
</option>
<option value="Turner">
Turner
</option>
<option value="Valley Falls">
Valley Falls
</option>
<option value="Wakarusa">
Wakarusa
</option>
<option value="Wellsville">
Wellsville
</option>
<option value="Winchester">
Winchester
</option>
</select><select size="20">
</select><input type="text">
<div>
</div>
</div>
</div>
</div>
<div class="form-row">
<div class="form-left">
<label>Price:</label> <select class=
"dd-form-short" id="AskPrice1" name="AskPrice1"
onchange="showUser(this.value)">
<option value="">
Min Price
</option>
<option value="25000">
$25,000
</option>
<option value="50000">
$50,000
</option>
<option value="75000">
$75,000
</option>
<option value="100000">
$100,000
</option>
<option value="125000">
$125,000
</option>
<option value="150000">
$150,000
</option>
<option value="175000">
$175,000
</option>
<option value="200000">
$200,000
</option>
<option value="225000">
$225,000
</option>
<option value="250000">
$250,000
</option>
<option value="275000">
$275,000
</option>
<option value="300000">
$300,000
</option>
<option value="325000">
$325,000
</option>
<option value="350000">
$350,000
</option>
<option value="375000">
$375,000
</option>
<option value="400000">
$400,000
</option>
<option value="425000">
$425,000
</option>
<option value="450000">
$450,000
</option>
<option value="475000">
$475,000
</option>
<option value="500000">
$500,000
</option>
<option value="550000">
$550,000
</option>
<option value="600000">
$600,000
</option>
<option value="650000">
$650,000
</option>
<option value="700000">
$700,000
</option>
<option value="750000">
$750,000
</option>
<option value="800000">
$800,000
</option>
<option value="850000">
$850,000
</option>
<option value="900000">
$900,000
</option>
<option value="950000">
$950,000
</option>
<option value="1000000">
$1,000,000
</option>
</select>
</div>
<div class="form-right">
<label>To:</label> <select class=
"dd-form-short" id="AskPrice2" name="AskPrice2"
onchange="showUser(this.value)">
<option value="">
Max Price
</option>
<option value="25000">
$25,000
</option>
<option value="50000">
$50,000
</option>
<option value="75000">
$75,000
</option>
<option value="100000">
$100,000
</option>
<option value="125000">
$125,000
</option>
<option value="150000">
$150,000
</option>
<option value="175000">
$175,000
</option>
<option value="200000">
$200,000
</option>
<option value="225000">
$225,000
</option>
<option value="250000">
$250,000
</option>
<option value="275000">
$275,000
</option>
<option value="300000">
$300,000
</option>
<option value="325000">
$325,000
</option>
<option value="350000">
$350,000
</option>
<option value="375000">
$375,000
</option>
<option value="400000">
$400,000
</option>
<option value="425000">
$425,000
</option>
<option value="450000">
$450,000
</option>
<option value="475000">
$475,000
</option>
<option value="500000">
$500,000
</option>
<option value="550000">
$550,000
</option>
<option value="600000">
$600,000
</option>
<option value="650000">
$650,000
</option>
<option value="700000">
$700,000
</option>
<option value="750000">
$750,000
</option>
<option value="800000">
$800,000
</option>
<option value="850000">
$850,000
</option>
<option value="900000">
$900,000
</option>
<option value="950000">
$950,000
</option>
<option value="1000000">
$1,000,000
</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-left">
<label>Beds:</label> <select class=
"dd-form-short" id="Beds" name="Beds" onchange=
"showUser(this.value)">
<option value="">
Any #
</option>
<option value="1">
1 or more
</option>
<option value="2">
2 or more
</option>
<option value="3">
3 or more
</option>
<option value="4">
4 or more
</option>
<option value="5">
5 or more
</option>
<option value="6">
6 or more
</option>
</select>
</div>
<div class="form-right">
<label>Baths:</label> <select class=
"dd-form-short" id="Baths" name="Baths"
onchange="showUser(this.value)">
<option value="">
Any #
</option>
<option value="1">
1 or more
</option>
<option value="2">
2 or more
</option>
<option value="3">
3 or more
</option>
<option value="4">
4 or more
</option>
<option value="5">
5 or more
</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-left">
<label>Sq.Ft.:</label> <select class=
"dd-form-short" id="TotSQFT" name="TotSQFT"
onchange="showUser(this.value)">
<option value="">
Min SqFt
</option>
<option value="500">
Min 500
</option>
<option value="1000">
Min 1000
</option>
<option value="1500">
Min 1500
</option>
<option value="2000">
Min 2000
</option>
<option value="2500">
Min 2500
</option>
<option value="3000">
Min 3000
</option>
<option value="3500">
Min 3500
</option>
<option value="4000">
Min 4000
</option>
<option value="4500">
Min 4500
</option>
<option value="5000">
Min 5000
</option>
<option value="6000">
Min 6000
</option>
<option value="7000">
Min 7000
</option>
</select>
</div>
<div class="form-right">
<label>MLS#:</label> <input class=
"form-field-short" id="MLSNo" name="MLSNo"
onchange="showUser(this.value)" type="text">
</div>
</div>
<div class="form-row">
<input alt="Lawrence" class="search-button" id=
"Submit" name="Submit" value="Submit">
</div>
</div>
</form>
</div>
</div>
<div id="txtHint">
<b>Property Info Will Be Listed Here...</b>
</div>
</body>
</html>
-----------Now My GetUser.php----------------
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
<title></title>
</head>
<body>
<?php
$q = intval($_POST['q']);
$con = mysqli_connect('localhost','root','pw','properties');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"properties");
$sql= (need help here-table called `listings`) or die(mysql_error());
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Address</th>
<th>City</th>
<th>Zip</th>
<th>Beds</th>
<th>Baths</th>
<th>AskPrice</th>
<th>MLSNo</th>
<th>TotSQFT</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Address'] . "</td>";
echo "<td>" . $row['City'] . "</td>";
echo "<td>" . $row['Zip'] . "</td>";
echo "<td>" . $row['Beds'] . "</td>";
echo "<td>" . $row['Baths'] . "</td>";
echo "<td>" . $row['AskPrice'] . "</td>";
echo "<td>" . $row['MLSNo'] . "</td>";
echo "<td>" . $row['TotSQFT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
Something like this should be the solution. Because of the potential number of variables, the code to build the SQL ended up being fairly complicated. Apologies if there are any errors in there, I haven't got the tools to do any sort of testing available to me at the moment. But hopefully you see the pattern where we build up the WHERE clause of the SQL based on whether the user chose a value for each parameter or not (if they didn't, we allow any value in that column, so no need for a WHERE restriction on it)
The javascript submits the entire form via ajax (using jQuery's ajax functions, which are much easier to use than the raw XmlHTTP object) when the user clicks the "submit" button. I've done some very rudimentary validation, just to ensure the user selects at least one option to restrict the query, otherwise you could end up with a query just selecting everything from the database, which might be problematic.
Firstly, your HTML page:
<!DOCTYPE html>
<html>
<head>
<script type="Text/JavaScript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script type="text/javascript" language="javascript">
$(function() {
//adds an event listener to handle the form's "submit" event
$("#fs_quicksearch").submit(function(event) {
event.preventDefault(); //prevent the default postback behaviour
//make ajax request to the server
$.ajax({
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: 'text/html',
type: 'POST',
url: 'getuser.php',
data: $(this).serialize(), //automatically picks up all the form fields and translates them into a valid format for a POST request
success: function(response) { //runs when the request succeeeds (no HTTP errors)
$("#divResults").html(response);
},
error: function (jQXHR, textStatus, errorThrown) { //runs when the request fails with a HTTP error
alert("An error occurred whilst trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}
});
});
</script>
</head>
<body>
<form id="fs_quicksearch" name="fs_quicksearch">
<div class="form-container">
<div class="form-row form-row-loc">
<label for="City">Location:</label>
<select class="dd-form-long" id="City" name="City">
<option value="">Any City</option>
<option value="Auburn">Auburn</option>
<option value="Baldwin City">Baldwin City</option>
<option value="Basehor">Basehor</option>
<option value="Berryton">Berryton</option>
...rest of your options here
</select>
</div>
<div class="form-row">
<div class="form-left">
<label for="AskPrice1">Price:</label>
<select class="dd-form-short" id="AskPrice1" name="AskPrice1">
<option value="">Min Price</option>
<option value="25000">$25,000</option>
<option value="50000">$50,000</option>
...rest of your options here
</select>
</div>
<div class="form-right">
<label for="AskPrice2">To:</label>
<select class="dd-form-short" id="AskPrice2" name="AskPrice2">
<option value="">Max Price</option>
<option value="25000">$25,000</option>
<option value="50000">$50,000</option>
...rest of your options here
</select>
</div>
</div>
<div class="form-row">
<div class="form-left">
<label for="Beds">Beds:</label>
<select class="dd-form-short" id="Beds" name="Beds">
<option value="">Any #</option>
<option value="1">1 or more</option>
<option value="2">2 or more</option>
...rest of your options here
</select>
</div>
<div class="form-right">
<label for="Baths">Baths:</label>
<select class="dd-form-short" id="Baths" name="Baths">
<option value="">Any #</option>
<option value="1">1 or more</option>
<option value="2">2 or more</option>
...rest of your options here
</select>
</div>
</div>
<div class="form-row">
<div class="form-left">
<label for="TotSQFT">Sq.Ft.:</label>
<select class="dd-form-short" id="TotSQFT" name="TotSQFT">
<option value="">Min SqFt</option>
<option value="500">Min 500</option>
<option value="1000">Min 1000</option>
<option value="1500">Min 1500</option>
...rest of your options here
</select>
</div>
<div class="form-right">
<label for="MLSNo">MLS#:</label>
<input class="form-field-short" id="MLSNo" name="MLSNo" type="text">
</div>
</div>
<div class="form-row">
<input alt="Lawrence" class="search-button" id="Submit" value="Submit">
</div>
</div>
</form>
<br/>
<div id="divResults">
<b>Property Info Will Be Listed Here...</b>
</div>
</body>
Secondly, the PHP (there's no need for any of the raw HTML you had in getuser, you only want to return the table snippet, which will get added to the rest of the first page):
<?php
$city = $_POST['City'];
$askprice1 = $_POST['AskPrice1'];
$askprice2 = $_POST['AskPrice2'];
$beds = $_POST['Beds'];
$baths = $_POST['Baths'];
$totsqft = $_POST['TotSQFT'];
$mlsno = $_POST['MLSNo'];
//this is just some very crude validation, you should probably make it more sophisticated
if ($city == "" && $askprice1 == "" && $askprice2 == "" && $beds == "" && $baths == "" && $totsqft == "" && $mlsno == "")
{
echo "Validation error: Please choose at least one option";
}
else
{
$con = mysqli_connect('localhost','root','pw','properties');
if (mysqli_connect_errno())
{
echo "Failed to connect: " . mysqli_connect_error();
}
mysqli_select_db($con, "properties") or die('ERROR! Could not select database');
//build the sql based on what the user selected
$sql = "select * from `listings` where ";
$paramArr = array(); //will contain the query parameters.
$paramTypes = ""; //will indicate the data type of each parameter
$sqlwhere = "";
if ($city != "") { $sqlwhere .= " City = ?"; $paramArr[] = $city; $paramTypes .= "s";}
if ($askPrice1 != "") { $sqlwhere .= ($sqlwhere == "" ? "" : " and ")." AskPrice >= ?"; $paramArr[] = &$askPrice1; $paramTypes .= "i";}
if ($askPrice2 != "") { $sqlwhere .= ($sqlwhere == "" ? "" : " and ")." AskPrice <= ?"; $paramArr[] = &$askPrice2; $paramTypes .= "i";}
if ($beds != "") { $sqlwhere .= ($sqlwhere == "" ? "" : " and ")." Beds >= ?"; $paramArr[] = &$beds; $paramTypes .= "i";}
if ($baths != "") { $sqlwhere .= ($sqlwhere == "" ? "" : " and ")." Baths >= ?"; $paramArr[] = &$baths; $paramTypes .= "i";}
if ($totsqft != "") { $sqlwhere .= ($sqlwhere == "" ? "" : " and ")." TotSQFT >= ?"; $paramArr[] = &$totsqft; $paramTypes .= "i";}
if ($mlsno != "") { $sqlwhere .= ($sqlwhere == "" ? "" : " and ")." MLSNo = ?"; $paramArr[] = &$mlsno; $paramTypes .= "s";} //if the MLSNo column in the DB is actually an integer, you'll need to change "s" to "i" here
$sql .= $sqlwhere;
$initialParams = array(&$stmt, &$paramTypes);
$callbackParams = array_merge($initialParams, $paramArr);
$statement = mysqli_prepare($con, $sql); //use prepared statements to guard against SQL injection
call_user_func_array("mysqli_stmt_bind_param", $callbackParams)); //bind the parameters to the statement
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
echo "<table>
<tr>
<th>Address</th>
<th>City</th>
<th>Zip</th>
<th>Beds</th>
<th>Baths</th>
<th>AskPrice</th>
<th>MLSNo</th>
<th>TotSQFT</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Address'] . "</td>";
echo "<td>" . $row['City'] . "</td>";
echo "<td>" . $row['Zip'] . "</td>";
echo "<td>" . $row['Beds'] . "</td>";
echo "<td>" . $row['Baths'] . "</td>";
echo "<td>" . $row['AskPrice'] . "</td>";
echo "<td>" . $row['MLSNo'] . "</td>";
echo "<td>" . $row['TotSQFT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
}
?>
Lastly, one other small recommendation: Don't use the "root" account to log in to mysql from your web application. It can do anything, and you run a small risk that a malicious user could either steal the credentials, or manage to otherwise inject some malicious sql and then destroy your server, or steal data from your app. Set up a user specifically for this app, and give it permission only to the tables, procedures etc that it actually needs. That way you minimise the risk. I've used mysqli prepared statements as well which also minimises the risk of sql injection in the first place.

List box not working on HTML form linked to my mysql database

I have three list boxes on my HTML form,AUTHOR,GENRE and YEAR.These are linked to a sql database called Authors and a table called books.The idea is to click on one or all of the List boxes,the choice is then placed in variables then into a customised sql statement which extracts the data from the mysql DB and places the result in a table.The result only partly works.If I click one item from each box,then it reponds fine For Example EG Ken Davies(choice in author list) Adventure(choice in genre list) and 2007(choice in year list) Then this works fine.Also if I just click on an authors name,this works fine,or if I just click on genre,this works fine.However when I click on any of the years in the year list box,I dont get anything,despite the years working if I combine them into all three(authors,genre and year).Has anyone any suggestions please Many thanks.
<html>
<head>
<title>My Page</title>
</head>
<body>
<br>
<form name="myform" action="dropdown2.php" method="POST">
<select name="author" size="4">
<option value="ken davies">ken davies</option>
<option value= "arthur smith">arthur smith</option>
<option value="gill rafferty">gill rafferty</option><br />
<option value="molly brown">molly brown</option><br />
<option value="gilbert riley">gilbert riley</option><br />
<input type = "submit" name = "submit" value = "go">
<select name="genre" size="4">
<option value="adventure">adventure</option>
<option value="biography">biography</option>
<option value="crime">crime</option><br />
<option value="romance">romance</option>
<option value="2007">thriller</option>
<input type = "submit" name = "submit" value = "go">
<select name="year" size="4">
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<input type = "submit" name = "submit" value = "go">
<?php
$bird = ( ! empty($_POST['author'])) ? $_POST['author'] : null;
$cat = ( ! empty($_POST['genre'])) ? $_POST['genre'] : null;
$mouse = ( ! empty($_POST['year'])) ? $_POST['year'] : null;
$con = mysql_connect("localhost","root","");
If (!$con){
die("Can not Connect with database" . mysql_error());
}
Mysql_select_db("authors",$con);
if(isset($_POST['author'])&&isset($_POST['genre'])&&isset($_POST['year']))
{
$sql = "SELECT * FROM books WHERE author = '$bird' AND genre = '$cat' AND year = '$mouse' ";
unset($_POST['cat']);
unset($_POST['bird']);
unset($_POST['mouse']);
}
elseif(!isset($_POST['author']))
{
$sql = "SELECT * FROM books WHERE genre = '$cat' ";
unset($_POST['genre']);
}
elseif(!isset($_POST['genre']))
{
$sql = "SELECT * FROM books WHERE author = '$bird'";
unset($_POST['author']);
}
elseif(!isset($_POST['year']))
{
$sql = "SELECT * FROM books WHERE year = '$mouse'";
unset($_POST['author']);
unset($_POST['genre']);
unset($_POST['year']);
$myData = mysql_query($sql,$con);
echo"<table border=1>
<tr>
<th>id</th>
<th>author</th>
<th>title</th>
<th>publisher</th>
<th>year</th>
<th>genre</th>
<th>sold</th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['author'] . "</td>";
echo "<td>" . $record['title'] . "</td>";
echo "<td>" . $record['publisher'] . "</td>";
echo "<td>" . $record['year'] . "</td>";
echo "<td>" . $record['genre'] . "</td>";
echo "<td>" . $record['sold'] . "</td>";
echo "<tr />";
}
echo "</table>";
mysql_close($con);
?>
</form>
</body>
</html>
add mysql_error() for each query you have used and apart review your Html code it seems to be not pretty.
considering your database table name is books and its fields are title, author, genre, year and etc.
<?php
//database connection code here
?>
<form action="aaa.php" method="POST">
<table>
<tr>
<td>Author</td>
<td>
<select name="author">
<option value="">Select</option>
<?php
//gets all the name of the author in the database
$result1 = mysql_query("SELECT distinct author from books ORDER by author");
while($row1 = mysql_fetch_assoc($result2))
{
echo "<option>".$row21['author']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>Genre</td>
<td>
<select name="genre">
<option value="adventure">adventure</option>
<option value="biography">biography</option>
<option value="crime">crime</option><br />
<option value="romance">romance</option>
<option value="2007">thriller</option>
</select>
</td>
</tr>
<tr>
<td>Year</td>
<td>
<select name="year">
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
</select>
</td>
</tr>
<tr>
<td colspan="2"><input type="text" name="submit" value="submit"/></td>
</tr>
</table>
</form>
<?
if(isset($_POST['submit']))
{
echo "<table>";
$result = mysql_query("SELECT * from books where author='".$_POST['author']."' and genre='".$_POST['genre']."' and year='".$_POST['year']."' ");
while($row = mysql_fetch_assoc($result))
{
echo "<tr>":
echo "<td>".$row['title']."</td>":
echo "<td>".$row['author']."</td>":
echo "<td>".$row['genre']."</td>":
echo "<td>".$row['year']."</td>":
echo "</tr>":
}
echo "</table>";
}
?>

Populating select box with existing value

I have created a form which allows users to edit existing data within a database, I pull information from one page to the next to populate text boxes and select boxes. I have managed to populate the select box with the correct value but when the update statement goes through it deletes or doesn't recognize the pre-existing value. Can anyone help?
if (isset($_POST['submit'])) {
// Process the form
if (empty($errors)) {
$id = $brand["brandId"];
$brandName = mysql_prep($_POST["brandName"]);
$brandCategory = mysql_prep($_POST["brandCategory"]);
$brandKeyword = mysql_prep($_POST["brandKeyword"]);
$addedBy = mysql_prep($_SESSION['username']);
$query = "UPDATE brands SET ";
$query .= "brandName = '{$brandName}', ";
$query .= "brandCategory = '{$brandCategory}', ";
$query .= "brandKeyword = '{$brandKeyword}', ";
$query .= "addedBy = '{$addedBy}', ";
$query .= "dateTime = CURRENT_TIMESTAMP ";
$query .= "WHERE brandId = '{$id}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Brand updated.";
redirect_to("search.php");
} else {
// Failure
$_SESSION["message"] = "Brand update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<?php $layout_context = "user"; ?>
<?php include("../includes/layouts/header.php"); ?>
<?php include("../includes/layouts/navigation.php"); ?>
<div class="section">
<div id="message">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
</div>
<form id="edit_brands" action="edit_brands.php?id=<?php echo urlencode($brand["brandId"]); ?>" method="post">
<h2>Edit Brand Information: <?php echo htmlentities($brand["brandName"]);?></h2>
<p>
<label for="bname">Brand Name:</label>
<input class="textbox" id="bname" type="text" name="brandName" value="<?php echo htmlentities($brand["brandName"]); ?>" autofocus/>
</p>
<p>
<label for="bcategory">Brand Category:</label>
<select class="textbox" id="bcategory" type="text" name="brandCategory">
<option value=""><?php echo htmlentities($brand["brandCategory"]); ?></option>
<option value="Animation">Animation</option>
<option value="Automotive">Automotive</option>
<option value="Beauty and Fashion">Beauty & Fashion</option>
<option value="Comedy">Comedy</option>
<option value="Cooking and Health">Cooking & Health</option>
<option value="DIY">DIY</option>
<option value="Fashion">Fashion</option>
<option value="Film and Entertainment">Film & Entertainment</option>
<option value="Food and Drink">Food & Drink</option>
<option value="Gaming">Gaming</option>
<option value="Lifestyle">Lifestyle</option>
<option value="Music">Music</option>
<option value="News and Politics">News & Politics</option>
<option value="Science&Education">Science & Education</option>
<option value="Sports">Sports</option>
<option value="Technology">Technology</option>
<option value="Television">Television</option>
</select>
</p>
<p>
<label for="bkeyword">Brand Keyword:</label>
<textarea class="FormElement" id="bkeyword" name="brandKeyword" id="brandKeyword" placeholder=""><?php echo htmlentities($brand["brandKeyword"]); ?></textarea>
</p>
<p>
<input type="submit" class="button" name="submit" value="Edit Brand" onclick="return confirm('Do you wish to edit brand?');"/>
</p>
<p>
Cancel
</p>
</form>
</div>
</div>
The best way is to build the select from an array.
For instance:
<?php
$array = array('Animation', 'Automotive', 'Beauty and Fashion ', ...);
echo '<select class="textbox" id="bcategory" type="text" name="brandCategory">';
foreach ($array as $value){
if($value == htmlentities($brand["brandCategory"]){
echo '<option value='.$value.' selected>'.$value.'</option>';
}else{
echo '<option value='.$value.'>'.$value.'</option>';
}
}
echo '</select>;
This way you can check if the value in the array is the same that the one recieved by post and then add the selected attribute to the option tag.

Display output result in another page in PHP

I have a Tour Search application where user can search for available tours based on three different parameters- Region, Country and Duration. Currently the code which I am using is showing the Output Result in the same page. I want the output result to show in a different page.
Below is my PHP Code:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("byp");
if(isset($_POST['submit'])){
$region=$_POST['region'];
$country=$_POST['country'];
$duration=$_POST['duration'];
//define the index for the All option
$optionAllValue = 0; //add here the option index value used for the 'All' option
//define the where clause for the query
//in order to avoid many conditions verifications, we start it as 1=1
$whereClause = "1=1";
//now we check if the option selected for each field is not the value defined for the option 'All'
//this is just an example, and the best would be to create a function to avoid the replication of code
if($region != $optionAllValue)
{
$whereClause = $whereClause." and region='$region'";
}
if($country != $optionAllValue)
{
$whereClause = $whereClause." and country='$country'";
}
if($duration != $optionAllValue)
{
$whereClause = $whereClause." and duration='$duration'";
}
$query = "select * from byp_tour where ".$whereClause;
//original query select * from byp_tour where region='$region' and country='$country' and duration='$duration'"
$tour = mysql_query($query);
$tourNum = mysql_num_rows($tour);
if($tourNum >0){
while($result=mysql_fetch_array($tour)){
$tour_name = $result['tour_name'];
$tour_detail = $result['tour_detail'];
echo "Tour Name: $tour_name"; // HERE IS THE OUTPUT RESULT
echo "<br />";
echo "Tour Detail: $tour_detail";
echo "<br />";
echo "<br />";
echo "<br />";
}
}
else{
echo "No Tour Found";
echo "<br />";
echo "<br />";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>BYP Test</title>
</head>
<body>
<form action="searchtest.php" method="post">
<div>
<label>Region</label>
<select id="region" name="region">
<option value="0">All</option>
<option value="1">South East Asia</option>
<option value="2">Africa</option>
<option value="3">Europe</option>
<option value="4">America</option>
<option value="5">Australia</option>
</select>
</div>
<div>
<label>Country</label>
<select id="country" name="country">
<option value="0">All</option>
<option value="1">Cambodia</option>
<option value="2">Thailand</option>
<option value="3">Vietnam</option>
<option value="4">Myanmar</option>
<option value="5">Laos</option>
<option value="6">Ethiopia</option>
<option value="7">France</option>
<option value="8">New York City</option>
<option value="9">Melbourne</option>
</select>
</div>
<div>
<label>Duration</label>
<select id="duration" name="duration">
<option value="0">All</option>
<option value="1">5 Days</option>
<option value="2">10 Days</option>
</select>
</div>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
You need to add target="_blank" to <form>:
<form action="searchtest.php" method="post" target="_blank">

Assistance with a Search Function in PHP and MySQL

I am developing a Tour and Travel website and I have an option to allow my users to search Tours based on Region, Country and Duration.
Currently, the search option which I have developed allows to search tours and show results if all the search parameters match. For example, if a Tour is listed under Region- Africa, Country- Ethiopia and Duration- 5 Days, I have to select all the parameters to show up the Tour. But I want to modify the search option so that:
There would be a Select All option for Region, Country and Duration.
If someone searches using Select All option for all the three
parameters it would show all Tours available in the database.
If someone selects a Region only with the other two as Select All, it
would show only those tours which are listed under that Region. Same
with Country and Duration.
If someone selects only two parameters Like Country and Duration with
the third option as Select All, it would show only those tours which
are listed under the selected Country and Duration. Same with Region
and Duration.
Here is my Database Structure
The PHP code which I am using now is:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("byp");
if(isset($_POST['submit'])){
$region=$_POST['region'];
$country=$_POST['country'];
$duration=$_POST['duration'];
$tour = mysql_query("select * from byp_tour where region='$region' and country='$country' and duration='$duration'");
$tourNum = mysql_num_rows($tour);
if($tourNum >0){
while($result=mysql_fetch_array($tour)){
$tour_name = $result['tour_name'];
$tour_detail = $result['tour_detail'];
echo "Tour Name: $tour_name";
echo "<br />";
echo "Tour Detail: $tour_detail";
echo "<br />";
echo "<br />";
echo "<br />";
}
}
else{
echo "No Tour Found";
echo "<br />";
echo "<br />";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>BYP Test</title>
</head>
<body>
<form action="byptest.php" method="post">
<div>
<label>Region</label>
<select id="region" name="region">
<option value="0">Select</option>
<option value="1">South East Asia</option>
<option value="2">Africa</option>
<option value="3">Europe</option>
<option value="4">America</option>
<option value="5">Australia</option>
</select>
</div>
<div>
<label>Country</label>
<select id="country" name="country">
<option value="0">Select</option>
<option value="1">Cambodia</option>
<option value="2">Thailand</option>
<option value="3">Vietnam</option>
<option value="4">Myanmar</option>
<option value="5">Laos</option>
<option value="6">Ethiopia</option>
<option value="7">France</option>
<option value="8">New York City</option>
<option value="9">Melbourne</option>
</select>
</div>
<div>
<label>Duration</label>
<select id="duration" name="duration">
<option value="0">Select</option>
<option value="1">5 Days</option>
</select>
</div>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
There are some possibilities to follow on your code.
You can let the 0 index option on the selects to be "All", instead of being "Select".
E.g.
The regions select
<select id="region" name="region">
<option value="0">Select</option>
<option value="1">South East Asia</option>
<option value="2">Africa</option>
<option value="3">Europe</option>
<option value="4">America</option>
<option value="5">Australia</option>
</select>
will be transformed into
<select id="region" name="region">
<option value="0">All</option>
<option value="1">South East Asia</option>
<option value="2">Africa</option>
<option value="3">Europe</option>
<option value="4">America</option>
<option value="5">Australia</option>
</select>
Another possibility is to create a new option with a specific index, e.g., 9999;
This way you can modify your query in order to select all the elements depending on your selection.
The code should be modified to:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("byp");
if(isset($_POST['submit'])){
$region=$_POST['region'];
$country=$_POST['country'];
$duration=$_POST['duration'];
//define the index for the All option
$optionAllValue = 0; //add here the option index value used for the 'All' option
//define the where clause for the query
//in order to avoid many conditions verifications, we start it as 1=1
$whereClause = "1=1";
//now we check if the option selected for each field is not the value defined for the option 'All'
//this is just an example, and the best would be to create a function to avoid the replication of code
if($region != $optionAllValue)
{
$whereClause = $whereClause." and region='$region'";
}
if($country != $optionAllValue)
{
$whereClause = $whereClause." and country='$country'";
}
if($duration != $optionAllValue)
{
$whereClause = $whereClause." and duration='$duration'";
}
$query = "select * from byp_tour where ".$whereClause;
//original query select * from byp_tour where region='$region' and country='$country' and duration='$duration'"
$tour = mysql_query($query);
$tourNum = mysql_num_rows($tour);
if($tourNum >0){
while($result=mysql_fetch_array($tour)){
$tour_name = $result['tour_name'];
$tour_detail = $result['tour_detail'];
echo "Tour Name: $tour_name";
echo "<br />";
echo "Tour Detail: $tour_detail";
echo "<br />";
echo "<br />";
echo "<br />";
}
}
else{
echo "No Tour Found";
echo "<br />";
echo "<br />";
}
}
?>
The entire modified example can be found below:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("byp");
if(isset($_POST['submit'])){
$region=$_POST['region'];
$country=$_POST['country'];
$duration=$_POST['duration'];
//define the index for the All option
$optionAllValue = 0; //add here the option index value used for the 'All' option
//define the where clause for the query
//in order to avoid many conditions verifications, we start it as 1=1
$whereClause = "1=1";
//now we check if the option selected for each field is not the value defined for the option 'All'
//this is just an example, and the best would be to create a function to avoid the replication of code
if($region != $optionAllValue)
{
$whereClause = $whereClause." and region='$region'";
}
if($country != $optionAllValue)
{
$whereClause = $whereClause." and country='$country'";
}
if($duration != $optionAllValue)
{
$whereClause = $whereClause." and duration='$duration'";
}
$query = "select * from byp_tour where ".$whereClause;
//original query select * from byp_tour where region='$region' and country='$country' and duration='$duration'"
$tour = mysql_query($query);
$tourNum = mysql_num_rows($tour);
if($tourNum >0){
while($result=mysql_fetch_array($tour)){
$tour_name = $result['tour_name'];
$tour_detail = $result['tour_detail'];
echo "Tour Name: $tour_name";
echo "<br />";
echo "Tour Detail: $tour_detail";
echo "<br />";
echo "<br />";
echo "<br />";
}
}
else{
echo "No Tour Found";
echo "<br />";
echo "<br />";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>BYP Test</title>
</head>
<body>
<form action="byptest.php" method="post">
<div>
<label>Region</label>
<select id="region" name="region">
<option value="0">All</option>
<option value="1">South East Asia</option>
<option value="2">Africa</option>
<option value="3">Europe</option>
<option value="4">America</option>
<option value="5">Australia</option>
</select>
</div>
<div>
<label>Country</label>
<select id="country" name="country">
<option value="0">All</option>
<option value="1">Cambodia</option>
<option value="2">Thailand</option>
<option value="3">Vietnam</option>
<option value="4">Myanmar</option>
<option value="5">Laos</option>
<option value="6">Ethiopia</option>
<option value="7">France</option>
<option value="8">New York City</option>
<option value="9">Melbourne</option>
</select>
</div>
<div>
<label>Duration</label>
<select id="duration" name="duration">
<option value="0">All</option>
<option value="1">5 Days</option>
</select>
</div>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
I have noticed your Selects are interdependents. It means you need to update the current options in cascade after on of the Selects are modified. To be able to do execute the cascading you can reference other questions on StackOverflow: cascading dropdowns from mysql with javascript and php
You have to build up your query depending on what variables are set. You could do something like:
$where = '';
if (!empty(($duration)) {
$where = " AND duration='$duration'";
}
if (!empty($country)) {
$where = " AND duration='$country'";
}
if (!empty($duration)) {
$where = " AND duration='$duration'";
}
$where = substr($where, 5);
$sql = "select * from byp_tour" . ($where ? " WHERE $where" : '');
$tour = mysql_query($sql);
Im no PHP whiz but I would first in your HTML form you would want a "Select All" (unless that's what you already mean by "Select")
If you did "Select All" Value = "0" Then after you check for form submission with your:
if(isset($_POST['submit'])){
YOu would then need if statements to check for any field that has a Value of "0". If a field is Set to 0 you would then want to remove that part of your database query.
For Ex. If Region = Select All then in your query remove region='$region'
That way you are not returning 0 results as your Region field should not have any region of 0.
Hope that kind of makes sense.

Categories