I am quite new at coding such things as I am asking so I would appreciate if someone could perhaps help me out.
I am looking to do an MYSQL search and echo based on variables selected in a drop-down menu. I am not too sure on how to search 1 inputted variable let alone multiple based on the selected. I would like it to be a filtering system.
Here is my form:
<form>
<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true">
<legend>Horizontal, mini sized:</legend>
<label for="select-h-6a">Select A</label>
<select name="select-h-6a" id="select-h-6a">
<option value="#">One</option>
<option value="#">Two</option>
<option value="#">Three</option>
</select>
<label for="select-h-6b">Select B</label>
<select name="select-h-6b" id="select-h-6b">
<option value="#">One</option>
<option value="#">Two</option>
<option value="#">Three</option>
</select>
<label for="select-h-6c">Select C</label>
<select name="select-h-6c" id="select-h-6c">
<option value="#">One</option>
<option value="#">Two</option>
<option value="#">Three</option>
</select>
</fieldset>
</form>
(would I need a submit button to send the query?)
Here is the code I am using to get posts at the moment:
$posts = getAllPosts();
<div id="searchpost">
<div class="ui-bar ui-bar-a">
<div id="postTitle">
<?php echo $posts[$p]["post_title"];?></div>
</div>
<div class="ui-body ui-body-a">
<div id="postContent">
<?php echo $posts[$p]["post_content"];}?></div>
</div>
</div>
and the functions for that:
function getAllPosts() {
require "config.php";
$posts = $c->query ( "SELECT * FROM posts" );
if ( $posts->num_rows > 0 ) {
while( $row = $posts->fetch_assoc() ) {
$postData[] = array( "user_id" => $row[ "user_id" ], "post_title" => $row[ "post_title" ], "post_content" => $row[ "post_content" ] );
}
} else {
return "No Data";
}
return $postData;
}
Posting the data:
<div id="postTitle">
<?php echo $posts[$p]["post_title"];?></div>
</div>
<div class="ui-body ui-body-a">
<div id="postContent">
<?php echo $posts[$p]["post_content"];}?></div>
</div>
However, as you can see, it calls for things in the database specifically. How can I make what I select in the drop down menus be shown instead of the specifics?
Can this be added for multiple selected options such as selecting rock, singer and 2 members showing only the records that all three of those in it? I assume if I don't want something specific in option 2 I can have an all option which searches for everything in that category.
My database: Image
Connection: (config.php)
<?php
$c = mysqli_connect( "localhost", "user", "pass", "database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
So, I need help with:
- putting the drop down options into variables
- having those variables be put into an MYSQL search query
I think the variables are the key here but I am not too sure on how to do it.
I hope you understand what I am needing help with. If not please ask questions :) Thank you so much xx
Related
I am kinda new in JavaScript and need some help.
I have a search form in my navigation menu.
Here is my code php+html for the form.
<form action="search.php" name="form-name" method="GET" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-2 col-md-12 col-sm-12 search">
<label>Destination</label>
<select required name="country" id="destination" onChange="getCity(this.value);">
<option value="">Any destination</option>
<?php $query = "SELECT * FROM countries";
$select_region_query = query($con, $query);
while ($row = fetch($select_region_query)) {
$region_id = $row['country_id'];
$region_name = $row['country_name'];
echo "<option value='".str_replace("&", "and",$full_region)."'>$full_region</option>";
}
?>
</select>
</div>
<div class="col-lg-2 col-md-12 col-sm-12 search ">
<label>City</label>
<select name="city" id="city" onChange="get_dropdown_ajax(this.value);">
<option value="">Any Cruise Line</option>
<?php $query = "SELECT * FROM cities";
$select_city_query = query($con, $query);
while ($row = fetch($select_city_query)) {
$city_id = $row['city_id'];
$city_name = $row['city_name'];
$city_name_value = str_replace("&"," and ",$row['city_name']);
echo "<option value='$city_name_value'>$city_name</option>";
}
?>
</select>
</div>
<div class="input-group col-lg-4 col-md-12 col-sm-12 search">
<label>Dates</label>
<select name="date_1" id="date_1">
<option value="">Any Day</option>
<?php
for($i=0;$i<31;$i++){
$i = str_pad($i,2,"0",STR_PAD_LEFT);
echo "<option value='$i'>$i</option>";
}
?>
</select>
<select name="date" id="date">
<option value="">Any Month</option>
<?php
for ($i = 0; $i <= 36; $i++) {
$time = strtotime(sprintf('+%d months', $i));
$value = date('Y-m', $time);
$label = date('F-Y', $time);
$label = str_replace("-", " ", $label);
echo "<option value='$label'>$label</option>";
}
?>
</select>
<input type="hidden" id="datepicker">
</div>
<div>
<button type="submit" name="search" class="search_button_nav btn btn-info">
<span class="glyphicon glyphicon-search"></span></button>
</div>
</div>
</form>
What I need to achieve is when the user doing a search to get these URL parameters and use these to change my select options based on their choices.
e.g If they search for country United Kingdom on search page my dropdown on countries to display United Kingdom instead of Any Destination.
I tried to do that with php $_GET but I am not sure is a good idea, because my country list is really big and I can create for every country if(issets($_GET)=='United Kingdom)' etc..
Is that something can complete with javascript without have to check the query of url like i tried with php?
I seach for solution and I find on other posts that (window.location); probably can help me.
I tried to console.log(window.location) and I can see the parameters, but how can I split them properly and use them with php?
Any feedback would be helpful.
P.S My url is looking like this one : nameofmysite/search.php?country=+United+Kingdom&chk=1&city_name=%25date_1=05&date=July+2018
I am not sure whether I understand your problem If you just want to set the dopdown-item to the city the user is searching for, using $_GET is no bad idea. You just have to check whether the parameter is given, then you can use it in PHP.
if(isset($_GET['search'])) {
echo "<option value='".$_GET['search']."'>".$_GET['search']."</option>";
} else {
echo "<option value=''>Any destination</option>";
}
I think you are trying to mix the use of the parameter.
Once the request is sent, the server will process that request and interpret the PHP page in the server before send it to the client (the browser). If you need to check a parameter then you can get it with the global variable $_GET and do whatever you want and build your page conveniently.
Get request parameters from URL in PHP GET URL parameter in PHP
Once the page is built it is sent to the client wich interpret it and your browser renders it. Then you can get the URL with window.location and parse it conveniently with split method or Regular expressions to get what you want from there.
Get request parameters from URL in Javascript How to get URL parameters with Javascript?
But the page is already rendered and what you can do then is manipulate the DOM of the page.
So I understand if this may take a while to process but I have a dropdown box and what it's meant to do is if certain selections are clicked then it will fetch info in the database depending on what they selected. My question is, why aren't my if statements working when I have applied a session onto each selection and am fetching them based on the ones clicked.
Here is the HTML:
<div class="button_wrap">
<select name="makeSelectLeft" class="compareButtonSizing" required="required" multiple="multiple">
<option>Make</option>
<?php session_start(); $_SESSION['MitOne']="Mitsubishi1" ?><option value="Mitsubishi1">Mitsubishi</option>
<?php session_start(); $_SESSION['SubOne']="Subaru1" ?><option value="Subaru1">Subaru</option>
<?php session_start(); $_SESSION['ToyOne']="Toyota1" ?><option value="Toyota1">Toyota</option>
</select>
<select name="modelSelectLeft" required="required" multiple="multiple">
<option>Model</option>
<?php session_start(); $_SESSION['LancOne']="Lancer1" ?><option value="Lancer1">Lancer</option>
<?php session_start(); $_SESSION['EvoOne']="Evolution1" ?><option value="Evolution1">Evolution</option>
<?php session_start(); $_SESSION['CamOne']="Camry1" ?><option value="Camry1">Camry</option>
</select>
<select name="yearSelectLeft" required="required" multiple="multiple">
<option>Year</option>
<?php session_start(); $_SESSION['1982 - 1983']="1982 - 1983" ?><option value="1982 - 1983">1982 - 1983</option>
<?php session_start(); $_SESSION['1983 - 1991']="1983 - 1991" ?><option value="1983 - 1991">1983 - 1991</option>
<?php session_start(); $_SESSION['1988 - 1995']="1988 - 1995" ?><option value="1988 - 1995">1988 - 1995</option>
<?php session_start(); $_SESSION['1995 - 2000']="1995 - 2000" ?><option value="1995 - 2000">1995 - 2000</option>
<?php session_start(); $_SESSION['2000 - 2007']="2000 - 2007" ?><option value="2000 - 2007">2000 - 2007</option>
<?php session_start(); $_SESSION['2007 - 2017']="2007 - 2017" ?><option value="2007 - 2017">2007 - 2017</option>
</select>
</div>
Thats where I added in the starts for the sessions. There is a session for each selection. In the PHP I currently have three outputs no matter what options I select. It's supposed to only have one and show one depending on what Make, Model, and Year you have selected.
Here is the PHP:
<?php
session_start();
if (!empty($_SESSION['MitOne']) && ($_SESSION['LancOne']) && ($_SESSION['1982 - 1983'])) {
$MitFirstState = mysql_query("SELECT Max_Speed FROM CarSpecifications WHERE id=2");
while ($MitFirstFetch = mysql_fetch_array($MitFirstState)) {
print_r($MitFirstFetch[0]);
}
}
if (!empty($_SESSION['SubOne']) && ($_SESSION['LegOne']) && ($_SESSION['1982 - 1983'])) {
$SubFirstState = mysql_query("SELECT Max_Speed FROM CarSpecifications WHERE id=3");
while ($SubFirstFetch = mysql_fetch_array($SubFirstState)) {
print_r($SubFirstFetch[0]);
}
}
if (!empty($_SESSION['ToyOne']) && ($_SESSION['CamOne']) && ($_SESSION['1982 - 1983'])) {
$ToyFirstState = mysql_query("SELECT Max_Speed FROM CarSpecifications WHERE id=4");
while ($ToyFirstFetch = mysql_fetch_array($ToyFirstState)) {
print_r($ToyFirstFetch[0]);
}
}
?>
The main thing I don't understand is why the if statements aren't working. I have tried putting else statements on there and changing the isset/empty variables and all of it. It doesn't seem to work.
Again I apologise for the large amount of info. If someone could help that would be greatly appreciated.
P.S. If someone has a javascript solution they are welcome.
Thank You.
Request-Response is actually simpler than you're trying to attempt.
Your request session in 2nd file will have values initialised for parameters "makeSelectLeft, modeSelectLeft and yearSelectLeft" in the $_REQUEST object. These values are data in "value" attribute of "option".
<option value="Mitsubishi1">
Hence this php snippet is redundant. Remove these from your HTML.
<?php session_start(); $_SESSION['MitOne']="Mitsubishi1" ?>
In your PHP code, $_REQUEST['makeSelectLeft'] will give all values of options selected by user. Similarly you can retrieve data for others. Following that, make your database queries etc.
None of this is being executed properly. As mentioned, you need your session_start(); one time and at the top of the page. Second you need to take advantage of form submission values, not session values. Last, you have to submit the form or use AJAX to process the user's selections. Here is an example (submission of the form is required, you would need to research ajax to do dynamic selections):
<?php
# I'm not convinced you even need this in your example, but you only put it
# once at the top of the page
session_start();
# Process the submission
if(!empty($_POST['action']) && $_POST['action'] == 'do_options') {
# Here is where you do your if conditions based on the post, not session
print_r($_POST['selectleft']);
}
?>
<!--
....html on your page...etc.
-->
<form action="" method="post">
<input type="hidden" name="action" value="do_options" />
<div class="button_wrap">
<select name="selectleft[make]" class="compareButtonSizing" required="required" multiple="multiple">
<option value="">Make</option>
<option value="Mitsubishi1">Mitsubishi</option>
<option value="Subaru1">Subaru</option>
<option value="Toyota1">Toyota</option>
</select>
<select name="selectleft[model]" required="required" multiple="multiple">
<option value="">Model</option>
<option value="Lancer1">Lancer</option>
<option value="Evolution1">Evolution</option>
<option value="Camry1">Camry</option>
</select>
<select name="selectleft[year]" required="required" multiple="multiple">
<option>Year</option>
<option value="1982_1983">1982 - 1983</option>
<option value="1983_1991">1983 - 1991</option>
<option value="1988_1995">1988 - 1995</option>
<option value="1995_2000">1995 - 2000</option>
<option value="2000_2007">2000 - 2007</option>
<option value="2007_2017">2007 - 2017</option>
</select>
</div>
<input type="submit" value="SAVE" />
</form>
I have multiple dropdowns and want to filter the contents of the second dropdown based on what is selected in the first dropdown. Here is the following code that I have so far. How could I do this?
HTML/PHP:
<td>
<select id="major" onChange="updateCat();">
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
JavaScript:
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
Database connection and SQL statements:
<?php
$host="xxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM ProductTable ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM ProductTable ORDER BY [Minor Category] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
?>
Sorry don't have much time can't make your answer for your code but giving you an example which will surely help you. run snippet below.
HTML
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br>
<select id="second"></select>
and Javascript
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
this code will work for you but try to use JSON for sending options to user and then apply some if else statement according to user selection of first drop down.
Tip: If you have large no. of options in select statement or large no. of select statements in your code then go and learn AJAX First. its easy and simple you can learn it easily. JSON and AJAX hardly takes 2-3 days.In Ajax call function according to user selection and send data using JSON. Although Ajax increases no. of request to server but it will decrease code length. which decreases page load time, easy to maintain, and good for search engine. Google love pages with less code and more information and will help you in future too to solve lots of problems easily.
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br><br>
<select id="second"></select>
I'm using Laravel and currently creating a form, where users can first choose a category, and then choose a relating subcategory.
A category has an id and a name, a subcategory has an id and a name, as well as a parent_id (so that's the id of the parent category).
Now I try the following:
The user can pick a category, after he did that, the second select appears and the user can choose the subcategory from the subcategories that belong to the parent category (and only those!).
Therefore, the view gets all categories and all subcategories from the controller.
Then, for the categories I did this:
<div class="form-group{{ $errors->has('category') ? ' has-error' : '' }}">
<label for="category" class="col-md-4 control-label">Kategorie</label>
<div class="col-md-6">
<select>
#foreach($categories as $category)
<option value="<?php echo $category['id'];?>">{{$category->name}}</option>
#endforeach
</select>
</div>
</div>
And for the subcategories I have the same, just with subcategories:
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select>
#foreach($subCategories as $subCategory)
<option value="<?php echo $subCategory['id'];?>">{{$subCategory->name}}</option>
#endforeach
</select>
</div>
</div>
Now the question is: What I need to do is (in the subcategory foreach) a #if and check for the value of the chosen option of the category select and then check if($subcategory->parent_id == $chosenOptionID), to say it in pseudo code. How can I do this? I don't want to send the form or something, before somebody didn't choose the subcategory as well.... Of course, I maybe could send an ajax request to the controller whenever a category is chosen, then check the value of the option in the controller and send back the id. But this would cause very much traffic and would propably not be the best solution, so I'd like to do this only, if I don't get a better way to do....
PS: The question is not about hiding the subcategories when no category is chosen, thats basic js, I know how to do that. I only want to know, if it is possible to read the value of the category select while form is not sent yet.
EDIT: I now tried the AJAX thing but there seems to be a little error...
What I changed:
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select class="form-control" id="subCategorySelect">
</select>
</div>
</div>
The select is now empty and has an ID. Then in the same file I have the following JS:
<script>
$().ready(function(){
$('#categorySelect').change(function(){
var selectedOption = $('#categorySelect').find(":selected").val();
$.ajax({
url: '/getSubCategories',
data: {'id': selectedOption},
type: 'GET',
success: function (data) {
$('#subCategorySelect').html(data);
}
});
});
});
</script>
/getSubcategoriesroute points to the following function in my controller:
public function returnSubCategories(Request $request){
$subCategories = Subcategory::where('parent_id', '=', $request->id);
foreach($subCategories as $subCategory){
echo "<option value='$subCategory->id'>$subCategory->name</option>";
}
}
But it doesn't work.. The ajax request is defintely sent on selecting an option, as well the correct id is sent. But somehow nothing is outputted... Any ideas why?
I finally got it working with AJAX. This is my initial subCategorySelect.
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select class="form-control" id="subCategorySelect">
</select>
</div>
</div>
The select is now empty and has an ID. Then in the same file I have the following JS:
<script>
$().ready(function(){
$('#categorySelect').change(function(){
var selectedOption = $('#categorySelect').find(":selected").val();
$.ajax({
url: '/getSubCategories',
data: {'id': selectedOption},
type: 'GET',
success: function (data) {
$('#subCategorySelect').html(data);
}
});
});
});
</script>
/getSubcategoriesroute points to the following function in my controller:
public function returnSubCategories(Request $request){
$subCategories = Subcategory::where('parent_id', '=', $request->id)->get();
foreach($subCategories as $subCategory){
echo "<option value='$subCategory->id'>$subCategory->name</option>";
}
}
And it works perfectly.
hope this will help you understand how it works with php anyway for one selected option:
<div class="form-group">
<label class="control-label" for="country">Country:<span>*</span></label>
<select name="country" type="text" class="form-control" id="country">
<option value="">--Country--</option>
<?php
include "../db/db.php"; //db-connection cause i want to load a country list
$sql = "SELECT id, country_name FROM apps_countries ORDER BY country_name ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //check if an entry is there
while($row = $result->fetch_assoc()) { //get the values from the db
//now this is the part you have to implement in your script
if(isset($_POST["country"]) && $row["id"] == $_POST["country"]) { //check if country isset so if the user selected something
$optionSelected = "selected='selected'";
} else{
$optionSelected = "";
}
//your foreache loop goes here / add the value that is selected here
/*#foreach($categories as $category)
<option value="<?php echo $category['id']; ?>">{{$category->name}}</option> // get the associative array with "" and change it to $category["id"]
#endforeach*/
/**for my attempt it was this
{the id like as your category[id]} {set the selected here inside the option tag}
↓ ↓ */
$countrySet = "<option value='" .$row["id"]. "' ".$optionSelected.">".$row["country_name"]."</option>";
echo $countrySet;
}
}
$conn->close();
?>
</select>
</div>
Building a football prediction website. I am getting thee Home_team names and away team a names from fixtures table in DBMS, with corresponding drop down boxes for each fixture so that the user can predict the score. I cant get it to work. Grateful for any help!
//establish connection
<?php
$connection = mysql_connect('localhost', 'root', 'password');
mysql_select_db('mls');
$query = "SELECT * FROM fixtures WHERE Fixture_ID BETWEEN '1' and '10' ";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num>0){
echo"<table>";
echo "<th>Home Team</th>";
echo "<th>Home Score</th>";
echo "<th>Away Score</th>";
echo "<th>Away Team</th>";
for($count=0;$count<$num; $count++){
$row = mysql_fetch_array($result);
echo"<tr>
<td>".$row['Home_Team']."</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='H".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select >
</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='A".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td>".$row['Away_Team']."</td>
</tr>";
}
echo"</table>";
<input type="submit" title="Submit the form">
</form>
}
?>
<html>
<?php
//process3.php file
<?php
include_once('db.php');
$Home_Score = $_POST['Home_Score'];
$Away_Score = $_POST['Away_Score'];
if(mysql_query("INSERT INTO user_prediction VALUES('$Home_Score', '$Away_Score')")){
$result = "Successfully Inserted";
else
$result = "Insert failed";
?>
//myscript.js file
?>
$("#sub").click(function(){
$.post( $("#myForm).attr("action"), $("#myForm:input").serializeArray(),
function (info){$("#result").html(info);});
});
$("#myForm").submit(function(){
return false;
});
While there is plenty of things that could be causing problems, notice here:
<select name="Away_Score">
//count id for unique values in dropdown
<select id='A".$count."'>
$count will literally be represented here as the string "$count", due to this code not being contained in PHP tags. Try correcting instances of code similar to this to something like below:
<?php
echo '<select name="Away_Score">';
//count id for unique values in dropdown
echo '<select id="A' . $count . '">';
?>
I see some problems there..
you switch between PHP and HTML appearently without knowing what
is what or how you start PHP and end it.
Your table is messed
up. You open a table, but in mid you just forget about it. you dont
close your td-tags or your table.
your select is messed up. You
have 2 select tags, one of which has even unescaped php-code written
in it.
your JS click-event does not trigger, because you named
it wrong.
Apart from you using mysql_-functions, which are deprecated and will stop working in newer PHP vewrsions, the list goes on...
In short: This code is a complete mess. Erasing this and starting all over with a clear head would be the best option.
To digress a bit, I honestly think that for an app of that size you should be employing some open source PHP packages. Sorry I can't comment yet so had to leave as an answer