PHP HTML select box selected from MYSQL - php

A simple code that inserts a list of teams in select box.
I would like to set SELECTED team with a id , that is in HREF
http://localhost/teams.php?id=7&years=2011&cups=8
<?php
$query = "select distinct t.team_id,t.team from teams t,years y,cups c where t.team_id=c.team_id and y.year_id=$_GET[years] and c.cup_id=$_GET[cups] ORDER BY t.team ASC";
$res = mysql_query($query);
$option = '';
while($row = mysql_fetch_assoc($res))
{
$option .= '<option value = "'.$row['team_id'].'">'.$row['team'].'</option>';
}
?>
<form>
<select id="tteam" name="team">
<?php echo $option; ?>
</select>
</form>
The problem is that I set team_id=$_GET[id], it shows only one team.
I want the team=7 to be selected, but others still be showing in select box

1st of all, NEVER EVER insert raw data into an SQL query. You are asking for SQL injections.
Secondly, you're missing quotes around your $_GET variables, for example, in your SQL query, you currently access id by using $_GET[id]. This won't work, encapsulate id in quotes, like $_GET['id'].
Thirdly, ESCAPE your data!!
mysql_* functions are now deprecated. You shouldn't be using them in new code. Instead, look into PDO or MySQLi functionality. Also look into prepared queries.
This should be your code:
<?php
$years = mysql_real_escape_string($_GET['years']);
$cups = mysql_real_escape_string($_GET['cups']);
$query = "SELECT distinct t.team_id, vt.team
FROM teams t,years y,cups c
WHERE t.team_id = c.team_id
AND y.year_id = '{$years}'
AND c.cup_id = '{$cups}'
ORDER BY t.team ASC";
$res = mysql_query($query);
$option = '';
while($row = mysql_fetch_assoc($res))
{
// The line below specifies whether the option should be selected.
$selected = $row['team_id']==$_GET['id'] ? 'selected="selected"' : '';
$option .= '<option ' . $selected . ' value= "' . $row['team_id'] . '">' . $row['team'] . '</option>';
}
?>
<form>
<select id="tteam" name="team">
<?php echo $option; ?>
</select>
</form>

Please be aware that you're vulnerable to SQL injections. See: How can I prevent SQL injection in PHP?
With that said, you need to use a conditional statement that compares $row["team_id"] with $_GET["ID"].
while($row = mysql_fetch_assoc($res))
{
if($row["team_id"] == $_GET["ID"])
$option .= '<option value = "'.$row['team_id'].'" selected="selected">'.$row['team'].'</option>';
else
$option .= '<option value = "'.$row['team_id'].'">'.$row['team'].'</option>';
}

while($row = mysql_fetch_assoc($res))
{
$option .= '<option value = "'.$row['team_id'].'" '.($row['team'] == 7 ? 'selected="selected"': '').'>'.$row['team'].'</option>';
}

Compare your id from $_GET with $row['team_id'].
while($row = mysql_fetch_assoc($res))
{
if($row['team_id'] == $_GET["id"])
$option .= '<option value = "'.$row['team_id'].'" selected="selected">'.$row['team'].'</option>';
else
$option .= '<option value = "'.$row['team_id'].'">'.$row['team'].'</option>';
}

I'll just focus on the loop part:
while($row = mysql_fetch_assoc($res))
{
$selected = (isset($_GET['team_id']) && $row['team_id'] == $_GET['team_id']) ? 'selected' : '';
$option .= '<option value = "'.$row['team_id'].'" selected="'. $selected .'">'.$row['team'].'</option>';
}

Related

How to add an additional option to an option form which is filled with a db query

How can I add an extra <option> with a value of all to:
<?php
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("tnews2") or die(mysql_error());
$query = "SELECT name,id,path FROM categories ORDER BY ID DESC LIMIT 0,6";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>
<select name="categories">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['path']."'>'".$row['name']."'</option>";
}
?>
</select>
I would be grateful for any suggestions
Edit
echo "<th>Tierart";
$query = $pdo->query("select sp_term from species");
//Abfrage der Tabelle Tierart
echo '<select name="sp_term">';
while ($sql_sp_term = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="all">all</option>';
echo '<option value="'.$sql_sp_term['sp_term'].'">'.$sql_sp_term['sp_term'].'</option>';
}
echo '</select>';
Since you're populating the values of option in a select tag section with a database query doing something as follows would do the trick.
echo '<select name="sp_term">';
while ($sql_sp_term = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$sql_sp_term['sp_term'].'">'.$sql_sp_term['sp_term'].'</option>';
}
echo '</select>';
However, when you want to add an additional item like All as an option, place an explicit option value before the while/after the while depending on your requirement and you'll have the select > option with the new All option added to the options from the database.
echo '<select name="sp_term">';
echo '<option value="all">all</option>';
while ($sql_sp_term = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$sql_sp_term['sp_term'].'">'.$sql_sp_term['sp_term'].'</option>';
}
echo '</select>';

multiple table make my data alsp multiply

<?php
$get = mysqli_query($conn, "SELECT supplier.*,product.* FROM
supplier,product ORDER BY supplier.supplierid ASC");
$option = '';
while ($row = mysqli_fetch_array($get, MYSQLI_ASSOC)) {
$option .= '<option value = "' . $row['productname'] . '">' .
$row['suppliername'] . '</option>';
}
<label style="margin-left:25px;margin-bottom: 10px; ">Supplier:
</label><select style="margin-bottom:10px ;margin-left: 50px;width:
200px"> <?php echo $option; ?></select>
Hello Maam And Sir I have A problem About that data Output In a Select Box. The thing that happen when i use this code or use two multiple table, the data output also double but if 1 table it is working the way i want. But I don't want to have a dirty codes that why i to put in a single query.

How to get selected value from dropdown list after submitting form in php

I would like to remain my drop down value which I select for submitting after posting the form. My form posts to the same page.
$query = "SELECT countryName,countryCode FROM tcf_countries";
$result = mysql_query ($query);
echo "Country: <select name='country' value=''>";
while($r = mysql_fetch_array($result)) {
$id = $r['countryCode'];
$cname = $r['countryName'];
echo "<option value=".$id.">".$cname."</option>";
}
echo "</select>"; ?>
Remove your current echo inside the loop and replace it with the following:
if($_POST["country"]==$id)
echo "<option value='".$id."' selected='selected'>".$cname."</option>";
else
echo "<option value='".$id."' >".$cname."</option>";
This will check if the current option being displayed is the one that was submitted and it will select it in that case.
If I understand what you are looking for correctly you need to use the $_POST value of your select to set the selected item...
$query = "SELECT countryName,countryCode FROM tcf_countries";
$result = mysql_query ($query);
$country = '';
echo "Country: <select name='country'>";
while($r = mysqli_fetch_array($result)) {
$id = $r['countryCode'];
$cname = $r['countryName'];
echo "<option value=".$id;
echo ($_POST["country"]==$id) ? ' selected="SELECTED"' : '';
echo ">".$cname."</option>";
}
echo "</select>"; ?>
Setting selected="SELECTED" for the $id that matches $_POST['country'] will make it the selected item in your dropdown.
And, get rid of mysql* functions and use mysqli* functions instead...

Populating dynamically generated select fields after submit using PHP value

I am trying to keep the answer that the user selected and display it once the form has been submitted and there are errors somewhere. This is so the form is not tedious and the user does not have to keep inserting the same values into the form once it has been submitted.
I have been successful in completing this for options that are not dynamically generated from database values:
<option
<?php if($_POST['condition'] == 'acceptable') {
echo 'selected="selected"';
}?> value="acceptable">Acceptable
</option>
That works fine! Now the problem is how do I do this for this form option?
<option value="select">- Select school -</option>
<?php
$result = mysqli_query($con,"SELECT `name` FROM school");
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['name'].'">'.$row['name'].' School</option>';}?>
</select>
I have tried this so far but I cannot get it to work:
$result = mysqli_query($con,"SELECT `name` FROM school");
while($row = mysqli_fetch_array($result)) {
if($_POST['school'] == '$row["name"]') {
$selected = 'selected="selected"';
}
echo '<option $selected value="'.$row['name'].'">'.$row['name'].' School</option>';}
You don't need to store that "selected" attribute in a variable,
just print it.
Dividing the echo to 2 allows you to insert a condition between them.
Another note: you did you wrapped the variable with '? You don't need to.
echo '<option value="'.$row['name'].'"';
if($_POST['school'] == $row["name"]) {
echo ' selected="selected"';
echo '>'.$row['name'].' School</option>';}?>
Change. In single qoutes echo doesnt interprets $selected as variable :
$result = mysqli_query($con,"SELECT `name` FROM school");
while($row = mysqli_fetch_array($result)) {
if($_POST['school'] == '$row["name"]') {
$selected = 'selected="selected"';
}
echo '<option '.$selected.' value="'.$row['name'].'">'.$row['name'].' School</option>';
}

Trying to make dynamic option form

OK I try this for days and I can't do it so I try to take it step by step first I need to get the info from the database correctly and show it in a form here is the database
CategoryID | CategoryName | ParentID
----------------------------------------
1 | FirstMenuCat1 | 0
2 | FirstMenuCat2 | 0
3 | SubMenuCat1 | 1
4 | SubMenuCat2 | 1
5 | SubMenuCat3 | 2
and here is my last attemp that worked so I know I get the correct data from database but I don't know how to make it a form:
<?php
require_once ('mysqli_connect.php');
$q = "SELECT CategoryName FROM menus where ParentID = '0' ORDER by CategoryID";
$r = #mysqli_query ($dbc, $q) or die("Error: ".mysqli_error($dbc));
/* associative array */
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
printf ("%s\n", $row["CategoryName"]);
}
?>
Here is my attempt to make it but its not working
/* associative array */
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
foreach($row){
echo "<option value=\"". urlencode( $_ ) ."\" $selected >$_</option>\n";
$selected = ""; // only the first element will be marked as selected
}
}
?>
Any ideas?
By looking at option tag i think you are trying to create a combobox list. If it is then First of all do not use \n. The options in a combobox list already shown line by line.
Secondly you have not printed the select tag. Without it the list will not be rendered properly. Try the following code:
echo "<select name='mylist'>";
$selected = "selected";
while (($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) !== FALSE){
echo "<option value='". $row['key']."' $selected >".$row['value']."</option>";
$selected = ""; // only the first element will be marked as selected
}
echo "</select>";
hopefully it may help.
Check this
echo '<select name="" id="">';
/* associative array */
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
// Check the $_ correctly
foreach($row){
echo "<option value='". urlencode( $_ ) ."'>$_</option>\n";
}
}
echo '</select>';
Note*: First element by default will be selected for the dd.
Not sure but I think this is what you need
$optionString = '';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$value = urlencode($row['CategoryName']);
$optionString .= "<option value='{$value}'>{$row['CategoryName']}</option>";
}
echo "<select>$optionString</select>";
$selected = 'selected';
$htmlSelect = '<select name="elementName" id="elementId">';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
$htmlSelect .= '<option value="' . urlencode( $_ ) . '" ' . $selected . ' >' . $_ . '</option>';
$selected = ""; // only the first element will be marked as selected
}
$htmlSelect .= '</select>';
echo $htmlSelect;
Note 1: It's better to use double quote " instead of single quote ' on element attributes. Some browsers don't like single quotes.
Note 2: Couldn't understand why you're using foreach again in the while statement.
Note 3: If you will not remember which option was selected there is not any need to specify which element is selected, first one will be selected by default.

Categories