Is it possible to query a mySQL Database using Optgroup? - php

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.

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];

PHP - Can't split the String and save the data in to database

I have a database with 3 tables (location,holidays and category)
I can insert the data in to holidays table but locationID and catID are NULL how can I insert the other information in locationID, locationName, country in Location table and catID, catDesc in Category table
I guess that I need to split the String in the (option value='..') and save it in 2/3 different variables and then to insert them in the tables but i don't know how.
Thanks
<?php
include 'database_conn.php';
$holidayTitle=$_POST['holidayTitle'];
$holidayDuration=$_POST['holidayDuration'];
$holidayPrice=$_POST['holidayPrice'];
$locationName=$_POST['locationName'];
$catDesc=$_POST['catDesc'];
if(isset($_POST['submit'])) {
$sql = "INSERT INTO PCH_holidays(holidayTitle, holidayDuration, holidayPrice)
VALUES ('$holidayTitle', '$holidayDuration', '$holidayPrice');";
$sql .= "INSERT INTO PCH_location (locationID)
VALUES ('$locationName');";
$sql .= "INSERT INTO PCH_category (catID)
VALUES ('$catDesc')";
if ($dbConn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $dbConn->error;
}
}
$dbConn->close();
?>
<form action="admin.php" method="POST">
<input type="text" name="holidayTitle" placeholder="Title">
<br>
<input type="text" name="holidayDuration" placeholder="Duration">
<br>
<input type="text" name="holidayPrice" placeholder="Price">
<br>
<select name="locationName">
<option value='l1, Milaidhoo Island, Maldives'>Milaidhoo Island, Maldives</option>
<option value='l2, Rangali Island, Maldives'>Rangali Island, Maldives</option>
<option value='l3, Zanzibar, Tanzania'>Zanzibar, Tanzania</option>
<option value='l4', Boston, USA>Boston, USA</option>
<option value='l5, San Francisco, USA'>San Francisco, USA</option>
<option value='l6, Nairobi, Kenya'>Nairobi, Kenya</option>
<option value='l7, Algarve, Portugal'>Algarve, Portugal</option>
<option value='l8, New York, USA'>New York, USA</option>
<option value='l9, Sorrento, Italy'>Sorrento, Italy</option>
<option value='l10, Verona, Italy'>Verona, Italy</option>
</select>
<br>
<select name="catDesc" >
<option value='c1,Luxury'>>Luxury</option>
<option value='c2,Tour'>Tour</option>
<option value='c3,Safari'>Safari</option>
<option value='c4,Golf'>Golf</option>
<option value='c5,Weddings'>Weddings</option>
<option value='c6,Walking'>Walking</option>
<option value='c7,Opera'>Opera</option>
</select>
<br>
<input type="submit" name="submit" value="send info">
</form>
I guess that I need to split the String in the (option value='..') and save it in 2/3 different variables and then to insert them in the tables but i don't know how.
That's pretty much it.
To split the string into 3 variables using your post data:
list($locationID, $locationName, $country) = explode(",", $_POST['locationName']);
Then change your SQL accordingly.
INSERT INTO PCH_location (locationID, locationName, country)
VALUES ('$locationID', '$locationName', '$country');
Repeat same thing with category table.
Note the comments you'll receive plenty about SQL security i.e. Prepared statements. The above should address your error.
If you are using drop downs for location and category, the values of the options should
be the ID's of the respective options, not the description/name. IOWs, they should be
numbers which you can then save directly to your holiday table. No parsing/manipulation required.
You have:
<option value='l1, Milaidhoo Island, Maldives'>Milaidhoo Island, Maldives</option>
But it should be:
<option value='1'>Milaidhoo Island, Maldives</option>
NOTE
Since you are storing the keys to the other two tables, you should not also store the text from these tables in the holiday table. If the name gets changed, you would have to do an update to the holiday table to update the descriptions. Not the best use of a relational database. Not a normalized structure.

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
}

Trying to populate a dropdown box from sql query in 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

set select <option> as selected in form

I have a form wich inserts some data in a mysql database.
This form contain a select and some options with their respective values like
<select name="car_type">
<option value="sport">Sports car</option>
<option value="van">Van</option>
<option value="large">Large family sedan</option>
<option value="small">Small city car</option>
</select>
The form can also be used to update a car's details in the database, it does so by loading the values from the database and fills the form automatically but I am stuck at making the <option> in the select, selected by default based on the value already set in the DB.
So if the user chooses to edit a car, lets say a car that already has Sports type filled in the DB, I want the form to automatically set the <option value="sport">Sports car</option> as selected, <option selected="selected" value="sport">Sports car</option>. By not doing this, the user has to choose again the type every time he submits the form, otherwise the first <option> and its value (sport) is sent by POST.
I am able to retrieve the value from the database by using $data['type'] but I did not find the exact php code to set the selected <option> to that in the database, can you guys help ?
Although the code looks messy, you can do something like this:
<select name="car_type">
<option value="sport" <?php if($data['type']=='sport') echo "selected='selected'"; ?> >Sports car</option>
<option value="van" <?php if($data['type']=='van') echo "selected='selected'"; ?>>Van</option>
<option value="large" <?php if($data['type']=='large') echo "selected='selected'"; ?>>Large family sedan</option>
<option value="small" <?php if($data['type']=='small') echo "selected='selected'"; ?>>Small city car</option>
</select>
<option value="large" <?php echo ($dbvalue=="large") ? "selected=\"selected\"" : "" ;?>>Large family sedan</option>
Work out the sql query bit yourself and replace my $dbvalue with the column data from your db
If you're trying to mark the active car type I would do it like this:
foreach ($car_types as $car_type){
echo '<option value="'.$car_type.'" '.($data['type']==$car_type?'selected':'').'>'.$car_type.'</option>';
}

Categories