Trying to populate a dropdown box from sql query in php - php

I need to populate a dropdown list based on the user's first dropdown selection, but before i even get that far I am just trying to populate one with a preselected team to make sure I get that part right first. However with this code I get my first dropdown with the team names, but then next to it is an empty text field and I can't seem to get the second dropdown to appear and populate. I am a newbie to html and php, I am fairly sure I'm missing something easy. Any help would be greatly appreciated and please let me know if I can be more clear about my issue. Thanks.
<!DOCTYPE html>
<html>
<head><style>
</style></head>
<body>
<form>
<select name="teams">
<option value="Atlanta Hawks ">Atlanta Hawks</option>
<option value="Boston Celtics ">Boston Celtics</option>
<option value="Charlotte Bobcats ">Charlotte Bobcats</option>
<option value="Chicago Bulls ">Chicago Bulls</option>
<option value="Cleveland Cavaliers ">Cleveland Cavaliers</option>
<option value="Dallas Mavericks ">Dallas Mavericks</option>
<option value="Denver Nuggets">Denver Nuggets</option>
<option value="Detroit Pistons ">Detroit Pistons</option>
<option value="Golden State Warriors">Golden State Warriors</option>
<option value="Houston Rockets ">Houston Rockets </option>
<option value="Indiana Pacers ">Indiana Pacers </option>
<option value="LA Clippers ">LA Clippers</option>
<option value="LA Lakers ">LA Lakers</option>
<option value="Memphis Grizzlies ">Memphis Grizzlies</option>
<option value="Miami Heat">Miami Heat</option>
<option value="Milwaukee Bucks ">Milwaukee Bucks</option>
<option value="Minnesota Timberwolves ">Minnesota Timberwolves</option>
<option value="New Jersey Nets">New Jersey Nets</option>
<option value="New Orleans Hornets ">New Orleans Hornets</option>
<option value="New York Knicks ">New York Knicks</option>
<option value="Oklahoma City Thunder ">Oklahoma City Thunder</option>
<option value="Orlando Magic ">Orlando Magic</option>
<option value="Philadelphia Sixers ">Philadelphia Sixers </option>
<option value="Phoenix Suns ">Phoenix Suns</option>
<option value="Portland Trail Blazers ">Portland Trail Blazers</option>
<option value="Sacramento Kings ">Sacramento Kings</option>
<option value="San Antonio Spurs ">San Antonio Spurs</option>
<option value="Toronto Raptors ">Toronto Raptors</option>
<option value="Utah Jazz">Utah Jazz</option>
<option value="Washington Wizards ">Washington Wizards</option>
</select>
<input type="text" name="team">
<?php
$con=mysqli_connect("localhost","nbastakm_josh","ateam","nbastakm_Stats");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT fname, lname FROM PlayerRegSeason WHERE team='NYK' and year='2009'";
$result = mysqli_query($con,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$playermenu = "
<p><label>Players</label></p>
<select name='players' id='players'>";
while($row=mysqli_fetch_array($result)){
$playermenu = "<option>".$row['lname']."</option>";
}
$playermenu = "</select>";
echo $playermenu;
mysqli_close($con);
?>
</form>
</body>
</html>

Use dot to concatenate strings:
while($row=mysqli_fetch_array($result)){
$playermenu .= "<option>".$row['lname']."</option>";
}
$playermenu .= "</select>";

it isn't possible to use client option without resending to server. you need:
ajax,
a second page (step 2 in wizard) were you can check the "teams" or
you can reload page with javascript after changing teams

Related

Simple Select Value will not Populate via Jscript if the word is "House"

I have a small Project website that I am learning to code with and in this website there is a Select Dropdown Menu of Music Genres
Here is a Video to help you visualise whats happening.
youtu.be/t4cJ7TCHiN8 (of the Problem)
And another video of how I can Paste "House" into the URL and get different MYSQL results
youtu.be/zf0S9WadQXo
I select a genre post the form and the reload shows me the results.
The value of the selected Option is then automatically selected by Jscript
So the Search area and its Values remain the same as before.
I have Mainly used DocumentGetElementById or jQuery to Select the value, and I am echoing PHP variables into the DocumentGetElementById function.
There is no problems with 99.9% of the values and selectable genres, they all are automatically selected without any problems.
Just 1 Problem, The value "House" Will not select.
No matter how I try it just will not select. I have of course tried other methods, including jQuery and no matter how I alter my code or method of execution.
Nothing seems to make the value "House" populate.
Here is the code. And images to help visualise the problem.
Thank you for any help you may provide.
CODE.
<select id='genregrab' name='genre' class='menusmall'>
<optgroup label='Genre'>
<option value="">All Genres</option>
<option value="EDM">EDM</option>
<option value="DnB">DnB</option>
<option value="Drum">Drum And Bass</option>
<option value="Breakbeat">Breakbeat</option>
<option value="Downtempo">Downtempo</option>
<option value="Dance">Dance</option>
<option value="Pop">Pop</option>
<option value="Disco">Disco</option>
<option value="Nu-Disco">Nu-Disco</option>
<option value="House">House</option>
<option value="Hard">Hard House</option>
<option value="Tech">Tech House</option>
<option value="Techno">Techno</option>
<option value="Deep">Deep House</option>
<option value="Future">Future House</option>
<option value="Tribal">Tribal House</option>
<option value="Tropical">Tropical House</option>
<option value="Progressive">Progressive</option>
<option value="Bass">Future Bass</option>
<option value="Bounce">Future Bounce</option>
<option value="Industrial">Industrial</option>
<option value="Electronic">Electronic</option>
<option value="Psychedelic">Psychedelic</option>
<option value="Trance">Trance</option>
<option value="Psy">Psy Trance</option>
<option value="Minimal">Minimal</option>
<option value="Ambient">Ambient</option>
<option value="Chillout">Chillout</option>
<option value="Synthwave">SynthWave</option>
<option value="Retro">Retro</option>
<option value="Hip">Hip-Hop</option>
<option value="Trip">Trip-Hop</option>
<option value="Glitch">Glitch-Hop</option>
<option value="Rap">Rap</option>
<option value="Afrobeat">AfroBeat</option>
<option value="Grime">Grime</option>
<option value="Trap">Trap</option>
<option value="Trapstep">TrapStep</option>
<option value="Dubstep">DubStep</option>
<option value="Drumstep">DrumStep</option>
<option value="Reggea">Reggea</option>
<option value="RnB">RnB</option>
<option value="Rock">Rock</option>
<option value="Metal">Metal</option>
<option value="Soul">Soul</option>
<option value="Country">Country</option>
<option value="Folk">Folk</option>
<option value="Jazz">Jazz</option>
<option value="Blues">Blues</option>
<option value="Funk">Funk</option>
<option value="World">World</option>
<option value="Gospel">Gospel</option>
<option value="Latin">Latin</option>
<option value="Ethnic">Ethnic</option>
<option value="Bollywood">BollyWood</option>
<option value="Moombahton">Moombahton</option>
<option value="Orchestral">Orchestral</option>
<option value="Classic">Classical</option>
<option value="Cinematic">Cinematic</option>
</optgroup>
</select>
Item Selected & POSTs Picked up By JScript to re-select the option
$(function(){
var genre = document.getElementById('genregrab');
var genredata = "<?php echo $genre ?>";
genre.value=genredata;
});
(Of course i initially tried the following)
document.getElementById("genregrab").value="<?php echo $genre ?>";
However unlike the others , the word "House" will not be selected.
I think its to do with the word or something, as every other word will work fine.
Same process just selecting another genre, and it works fine
As you can see , the Trance genre was selected
Just the word "House" has the problem.
And the Result after the Jscript
However , Select any other word and it works
As you can see in the image below
Any Ideas , Anybody?
I forgot to add the below code , from the GET and the MYSQL Results.
Its possible the sanitizing is effecting the variables.
The GET
if (isset($_GET['genre'])) {
$genre=$_GET['genre'];
$genre = filter_var($genre, FILTER_SANITIZE_STRING);
$genre = strip_tags($genre);
$genre = str_replace(['"',"'"], "", $genre);
} else {$genre="";}
And the MYSQL variable - Which also gets posted to the URL for GET
$genre=$row['genre'];
$genre = str_replace(['"',"'"], "", $genre);
if ($genre == "null" | $genre==" "){$genre="";}
$genresend = explode(',',trim($genre))[0];

How do I use PHP to query my SQL database using SELECT tag in html

Basically I'd like to use the choices which the user has selected from a different select tags, and in essence store these as variables which I can then use to query my database in SQL.
My HTML code is here:
<div id ="search_elements">
<img src="UniSelect.jpeg">
<select>
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select>
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
</div>
And the type of php i would be looking to use would be:
//$con=mysqli_connect("localhost","adam","YjM3ZTYwOTQ5OWRmYWZh","adam_...");
//if (mysqli_connect_errno())
// {
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
// }
// Perform queries
//$sql=mysqli_query($con,"SELECT CONTENT FROM Blog WHERE ID = 01");
//$result=mysqli_fetch_assoc($sql);
//echo $result['CONTENT'];
//mysqli_close($con);
To make it clear once more, I want to use the different values which the user selects, upon clicking a search button, have these query results shown in a table.
This solution a little differs from yours because you have no provided your form, submit button, etc. but in general, after a few changes, it should work too:
<form method="post" action="">
<img src="UniSelect.jpeg">
<select name="university">
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select name="rent_price">
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
<input type="submit" value="Submit form">
</form>
And now, to get values of these (something like this and I recommend to place it above your form):
if (!empty($_POST)) {
// Checking connection in here
$university_id = mysqli_real_escape_string($con, $_POST['university']);
$rent_price = mysqli_real_escape_string($con, $_POST['rent_price']);
$sql = mysqli_query($con, "SELECT * FROM university WHERE name = '".$university_id."'");
$result = mysqli_fetch_assoc($sql);
// Same thing goes for rent price
}

jquery.validationEngine.js dropwdown

Im using jquery.validationEngine.js everything is setup and working fine, however I need to make a change.
I have two dropdown boxes.
Is The Vehicle Imported? [yes, no]
What Is The Country Of Origin? [France, Germany, Japan, USA, UK] etc
What I require is that if the car is imported then to show the country of origin, else display nothing.
At the moment I have both fields working on a live form,
<label>Is The Vehicle Imported?</label>
<select class="validate[required] target" name="strLeadData39" id="strLeadData39">
<option selected="selected" value="">Please Select</option>
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
<label>What Is The Country Of Origin?</label>
<select class="validate[required] target" name="strLeadData40" id="strLeadData40" >
<option selected="selected" value="">Please Select</option>
<option value="Not Imported">Not Imported</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="Japan">Japan</option>
<option value="Canada">Canada</option>
<option value="USA">USA</option>
<option value="EU-Other">EU-Other</option>
<option value="Other">Other</option>
</select>
How do Ш complete this?
Thanks
So you want to show/hide the country select depending on the value of the imported select?
$('#strLeadData39').change(function(){
if ( $(this).val() == "Yes" ){
$('#strLeadData40').show();
} else {
$('#strLeadData40').hide();
}
});
Here is a fiddle with a basic example
The above code has nothing to do with jQuery validationEngine,just hiding/displaying the element. To make the form validate you will probably have to dynamically remove/add the validate[required] class using jQuery removeClass/addClass, something inside the if/else like:
$('#strLeadData40').removeClass("validate[required]");

Is it possible to query a mySQL Database using Optgroup?

For example, say I have the following code:
Choose a city:
<select name="city">
<optgroup label="East Coast Cities">
<option value="New York">New York</option>
<option value="Atlanta">Atlanta</option>
<option value="Miami">Miami</option>
</optgroup>
<optgroup label="West Coast Cities">
<option value="Las Vegas">Las Vegas</option>
<option value="Los Angeles">Los Angeles</option>
<option value="San Francisco">San Francisco</option>
</optgroup>
</select>
This will give me the correct drop down menu.. now.. say that each value is a also a value in my mySQL database. So for example, i have a table in my DB which also has these cities which is connected to a 900 row table with different people, each living in ONE of these cities.. What i would like to do is have it so that when someone selects a category it only searches for the people living in that city based on other specifications.. This is what I have in mind so far for the php file i'll use:
<?php $con=mysqli_connect("server","username","password","Database");
// Check connection
if (mysqli_connect_errno())
{
throw new Exception(mysqli_connect_error(), mysqli_connect_errno());
}
$city_query = $_POST['city'];
$result = mysqli_query($con,"SELECT name, address, city_name
FROM (People INNER JOIN City ON People.city_name = City.city_name)
WHERE city_name = $city_query");
//print out table using echo
mysqli_close($con); ?>
I hope this is fairly clear. Any help is appreciated, thank you.

How can I stop an empty SQL query from displaying all results?

I am creating a meat packaging search form, users can search for different packages using multiple forms and dropdown boxes. I have a had a lot of problems but most of it is sorted now, I only need to create an "Any" search for the dropdown boxes and the problem of empty textboxes displaying all results.
Currently when a user sends a search, they may have entered in some other text boxes, but when one of the forms is left empty that automatically displays all of the results. I want it so when a search is sent and a box is empty, the code ignores that form and just checks the ones that have info inside of them.
here is my test code (not my current final form code):
<body>
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("delyn_db", $con);
if (!$con)
{
die("Could not connect: " . mysql_error());
}
$descrip = mysql_real_escape_string($_POST['descrip']);
$sql = "SELECT * FROM delyn WHERE description LIKE '%" . $descrip . "%'";
$r_query = mysql_query($sql);
if ($descrip === "")
{
echo 'Null value';
}
while ($row = mysql_fetch_array($r_query))
{
echo '<br /> Description: ' . $row['description'];
}
?>
</body>
Anyone have any ideas on how to stop this?
EDIT: Sorry here is my HTML with the search boxes. The above php is just where the values are sent.
<body>
<form action="form5null.php" method="post">
<label for="description">Description:</label> <input type="text" name="descrip">
<br>
<label for="trayheight">Trayheight:</label> <input type="text" name="height">
<br>
<label for="traywidth">Traywidth:</label> <input type="text" name="width">
<br>
<label for="traydepth">Traydepth:</label> <input type="text" name="depth">
<br>
<label for="trayrange">Trayrange:</label> <select name="trayrange">
<option value="BBQ">
BBQ
</option>
<option value="Dessert">
Dessert
</option>
<option value="Display">
Display
</option>
<option value="Meat">
Meat
</option>
<option value="Microwave">
Microwave
</option>
<option value="Party">
Party
</option>
<option value="Salad/Wet Pasta">
Salad/Wet Pasta
</option>
<option value="Snacks">
Snacks
</option>
<option value="Standard">
Standard
</option>
</select> <label for="traytype">Traytype:</label> <select name="traytype">
<option value="Open">
Open
</option>
<option value="Cavitised">
Cavitised
</option>
<option value="Lid">
Lid
</option>
<option value="Tray">
Tray
</option>
<option value="Coallition">
Coallition
</option>
<option value="Bowl">
Bowl
</option>
<option value="Hinge pack">
Open
</option>
<option value="Pot">
Pot
</option>
<option value="Base & Lid">
Base and Lid
</option>
<option value="Rectangular">
Rectangular
</option>
<option value="Specalist">
Specialist
</option>
</select>
<br>
<label for="trayshape">Trayshape:</label> <select name="trayshape">
<option value="Rectangular">
Rectangular
</option>
<option value="Oval">
Oval
</option>
<option value="Square">
Square
</option>
<option value="Insert">
Insert
</option>
<option value="Round">
Round
</option>
<option value="Open">
Open
</option>
</select>
<br />
<input type="submit" value="Submit">
</form>
</body>
Add the following as the first option to all your dropdowns:
<option value="*">All</option>
Then use the SQL I provided in your duplicate question here:
Make SQL ignore a specific search value if clicked in a dropdown?
Dirk Nachbar gave a good answer as well.
Have you tried limiting your SQL queries by just checking if the values are blank/null (whichever is appropriate for PHP) and just not running the query if nothing is filled in?
e.g. (pseudocode)
if(box1.HasText || box2.HasText || box3.HasText)
{
RunTheSqlForForm1();
}

Categories