weird select drop down box error. content spilling out on page - php

Weird issue the country names are no longer being listed in the select dropdown box they're just spilling out all over the page. can anyone spot the coding error that is causing it?
echo "<select name=recordcountry style='width: 136px;'>";
//echo "<option value=$country selected=selected>-- Select --</option>";
echo "<option ". ($data['recordcountry'] == "" ? 'selected=selected>-- Select --</option>' : 'value="' .$data['recordcountry']. '" selected=selected');
$group1 = '<optgroup label=Common>';
$group2 = '<optgroup label=Alphabetically>';
$group = mysql_query("SELECT country, grouping, p_order FROM mast_country
WHERE grouping IN ('1','2') ORDER BY p_order");
while($row = mysql_fetch_array($group))
{
if ($row['grouping'] == '1')
{
$group1 .= '<option value="'.$row['country'].'">'.
$row['country'].'</option>';
}
else
{
$group2 .= '<option value="'.$row['country'].'">'.
$row['country'].'</option>';
}
$group1 .= '</otpgroup>';
$group2 .= '</otpgroup>';
echo $group1;
echo $group2;
echo "</select>";
}

It's </optgroup>, not </otpgroup>.
echo "<option ". ($data['recordcountry'] == "" ? 'selected=selected>-- Select --</option>' : 'value="' .$data['recordcountry']. '" selected=selected');
makes no sense, too. It is highly confusing and you are not adding </option>.
Here's a better version:
echo '<option value="'.$data['recordcountry'].'"'.($data['recordcountry'] ? '' : ' selected="selected"').'>'.($data['recordcountry'] ? $data['recordcountry'] : '--Select--').'</option>';
Or even better, split it into two lines and use an IF statement:
if($data['recordcountry'])
echo '<option value="'.$data['recordcountry'].'">'.$data['recordcountry'].'</option>';
else
echo '<option value="" selected="selected">--Select--</option>';

I think the problem is in this line.
echo "<option ". ($data['recordcountry'] == "" ? 'selected=selected>-- Select --</option>' : 'value="' .$data['recordcountry']. '" selected=selected');
No end tag is added when $data['recordcountry'] == "". Should be something like this i think.
echo "<option ". ($data['recordcountry'] == "" ? 'selected=selected>-- Select --</option>' : 'value="' .$data['recordcountry']. '" selected='selected'>" . $data['recordcountry'] . "</option>");
Edit: And what ThiefMaster said

Related

I have PHP form that is pulling information into a dropdown box from SQL Server. I want a particular item in the box as default selected

This code is pulling from DB table, and need it to display Information & Tecnology SVCS - 41515 as the default:
echo '<option value=" ' . $row['department']. '"' . ($row['department'] == "INFORMATION & TECHNOLOGY SVCS -41515") ? ' selected="selected"' : "".'>'.$row['department']. '</option>';
This Code will give me the drop down but not a selected define item:
echo ''.$row['department']. '';
Department:
<?php
$sql = "SELECT department FROM Department";
$query = sqlsrv_query($conn,$sql);
$query_display = sqlsrv_query($conn,$sql);
while($row=sqlsrv_fetch_array($query_display,SQLSRV_FETCH_ASSOC))
{
//echo '<option value=" '. $row['department'].' ">'.$row['department']. '</option>';
echo '<option value=" ' . $row['department']. '"' . ($row['department'] == "INFORMATION & TECHNOLOGY SVCS -41515") ? ' selected="selected"' : "".'>'.$row['department']. '</option>';
continue;
}
?>
</select>
</td>
Put parentheses around the conditional expression, because operator precedence is not what you're expecting.
echo '<option value=" ' . $row['department']. '"' . (($row['department'] == "INFORMATION & TECHNOLOGY SVCS -41515") ? ' selected="selected"' : "").'>'.$row['department']. '</option>';
To make it easier to read, I usually use a separate variable:
if ($row['department'] == "INFORMATION & TECHNOLOGY SVCS -41515") {
$selected = ' selected="selected"';
} else {
$selected = "";
}
echo '<option value=" ' . $row['department']. '"' . $selected .'>'.$row['department']. '</option>';
($row['department'] == "INFORMATION & TECHNOLOGY SVCS -41515")
There was a spacing issue. Needed to be
($row['department'] == "INFORMATION & TECHNOLOGY SVCS - 41515")

selecting option from select element with php

I have a database field country which I want to query and select that country option from a select element. Is there any way to do this without adding:
if (query->country == "<some country>"){echo "selected"}
in every single option tag? As there are hundreds of country options. Here is a little example of the code. Thank you.
$query = $query->fetch_object();
// which ever country is held in the variable `$query->country` should be selected
echo"<select>
<option>Afghanistan</option>
......
......
<option>Zimbabwe</option>
</select>";
Don't you have a list of all countries on your server?
$countries = ["Afghanistan", ... , "Zimbabwe"];
You could do something like this:
$selection = "Some country";
echo "<select>";
foreach($countries as $country)
{
if($country == $selection)
echo "<option selected>" . $country . "</option>";
else
echo "<option>" . $country . "</option>";
}
echo "</select>";
The IF still needs to be "placed" on every <option> but as a programmer you should do something like this:
$options = array( 'Afghanistan', '...', 'Zimbabwe' );
foreach( $options as $option )
{
$selected = ( $query->country == $option )? ' selected': '';
echo '<option' . $selected . '>' . $option . '</option>';
}
and if you're unfamiliar with ternary operator, the $selected = ... part above can be written like this:
if ( $query->country == $option )
{
$selected = ' selected';
}
else
{
$selected = '';
}

PHP In an Option Tag

Firstly apologies for asking this as it is quite basic but
I just can't seem to get it right. Have searched on here and
elsewhere for an answer (and tried various) but there is always
an error. Spent too long on this little bit and should really know
the answer but here goes:
Ok I have a main php file using an include statement to bring in a drop down menu
with the options being populated from a MySQL database. In the file being included I have this while loop which creates the
options and works fine:
while ($db_field = mysql_fetch_assoc($result)) {
$ManList2 = $db_field['categoryName'];
echo '<option value="' . $ManList2 . '">' . $ManList2 . '</option>';
}
What I want to add is something like the following in the option tag:
if($search == '$ManList2') { echo 'selected'; }
I just can't seem to get it right in the echo statement.
Any help greatly appreciated.
echo '<option value="'.$ManList2.'" '.($search == $ManList2 ? 'selected' : '').'>'.$ManList2.'</option>';
How about something like this:
while ($db_field = mysql_fetch_assoc($result)) {
$ManList2 = $db_field['categoryName'];
echo '<option value="' . $ManList2 . '"';
if($search == '$ManList2') {
echo ' selected';
}
echo '>' . $ManList2 . '</option>';
}
echo "<option value='".$ManList2; if($search == '$ManList2'){ echo 'selected'; } echo "'>".$ManList2."</option>";
You may try something like this (Assumed your select's name is search)
$search = isset($_POST['search']) ? $_POST['search'] : ''; // or $_GET maybe
$selected = '';
while ( $db_field = mysql_fetch_assoc($result) ) {
$ManList2 = $db_field['categoryName'];
$selected = $search == $ManList2 ? 'selected' : '';
echo '<option '.$selected.' value="'.$ManList2.'">'.$ManList2.'</option>';
}
You could use variables to put into your PHP, like:
while($db_field = mysql_fetch_assoc($result)) {
$ManList2 = $db_field['categoryName'];
$selected = $search === $ManList2 ? "selected='selected'" : '';
echo "<option value='$ManList2'$selected>$ManList2</option>";
}
I don't see what $search does, so this approach may not work. I would use my PHPglue Library. It handles this sort of thing for you.

PHP if/else statement doesn't produce the desired results

I have a dropdown menu populated from a table in a MySQL database. It functions, but I would like to add an if/else statement to the code to change the default value of the dropdown according to the conditions.
Here is the code for the dropdown (much thanks to AlienWebguy for his assistance in getting this far):
<?php
$sql="SELECT techID, tech_userlogin FROM technicians";
$result=mysql_query($sql);
while ($row=mysql_fetch_array($result))
{
$techID = $row['techID'];
$tech_userlogin=$row['tech_userlogin'];
// Here - check if the $_GET value in the query matches the tech_userlogin
($selected = ($tech_userlogin == $_GET['wtech_userlogin']) ? 'selected="selected"' : '');
echo '<option value="' . $tech_userlogin . '" ' . $selected . '>' . $tech_userlogin . '</option>' . "\n";
}
?>
I've tried a couple of things to accomplish what I'm after, but I'm severely hampered by my lack of experience and/or expertise in PHP/MySQL.
This is the first time I've tried these things and it has been hit and miss so far. I've recieved help here at Stack Overflow and I'm grateful such a resource exists.
This is my latest effort and it fails to achieve what I'm after. I want the default value of the dropdown to be "--Select Technician--" if the condition is not met in the if statement.
<?php
$sql="SELECT techID, tech_userlogin FROM technicians";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result))
{
$techID = $row['techID'];
$tech=$row['tech_userlogin'];
$options.="<option value=\"$tech\">$tech</option>";
// Here - check if the $_GET value in the query matches the tech_userlogin
if
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '')
{echo '<option value="' . $tech . '" ' . $selected . '>' . $tech . '</option>' . "\n";}
else
{echo '<option value="' . $options . '" . 'selected="selected"'>'--Select Tech--'<. $options .>' . "\n";}
}
?>
Can someone please help me or point me in the right direction? Many thanks.
Cheers
Try this
<select name="whatever">
<option value="">-- Select Technician --</option>
<?php while ($row = mysql_fetch_array($result)) :
$techId = $row['techID']; // why isn't this used?
$tech = htmlspecialchars($row['tech_userlogin']);
$selected = $row['tech_userlogin'] == $_GET['wtech_userlogin'] ? '" selected="selected' : '';
?>
<option value="<?php echo $tech, $selected ?>"><?php echo $tech ?></option>
<?php endwhile ?>
</select>
If the whole if/then is just there to create a default, you're making it way too complicated.
$options = '<option value="">--Select Tech--</option>';
while ($row=mysql_fetch_array($result))
{
$techID = $row['techID'];
$tech = $row['tech_userlogin'];
$selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '';
$options .= '<option value="' . $techID . '" ' . $selected . '>' . $tech . '</option>' . "\n";
}
Now $options has all of your options in it, including a default option (--Select Tech--, with empty value) that shows up first, and will therefore start out selected if nothing else has the selected attribute.
Note that you also had $tech in the value of your option, but I assumed you meant to say $techID.
You wrote this, which isn't doing what you want:
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '')
Change to this:
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : false)
Notice the 'false'. You need that because empty quotes is not false, it is considered 'true' by PHP.
I could be wrong, but I believe the problem is with your if statement. You have:
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '')
The problem is that you are assigning the result of the ternary statement to the variable $selected, which will always return a true for a successful assignment.

selected option in select dissappears on reload

Once it loads in my page, if nothing has been saved in the DB table, all options are shown. As soon as i make a selection and reload the page, the selected option dissapears from the list and isn`t reloaded in the dropdown. Instead, it displays the next value which takes the place of the selected one.
if i check the SQL statement and the $str, it does load all the options except the one which is selected which is in $getBris (it has a value).
What could be causing my select to not display my selected option and instead removing it from the list?
*It specifically doesnt work in IE8, wasnt working in Firefox but now it does
<script src="validation.js" type="text/javascript"></script>
<html>
<body onLoad="checkSecondValue();">
</body>
</html>
<?php
//retrieve all the bris for the drop down
include '../../inc/database.php';
// ORDER BY RAND()
$res = BbqcDatabase::getInstance()->doQuery('SELECT * FROM T_TOURNOI_BRIS');
$str = "<select name='ddlBrisSelected' id='ddlBrisSelected' onChange='checkSecondValue()'>";
$getBris = $_GET['bris'];
$getBris = $getBris - 1;
print_r("bris is : "+ $getBris);
if($getBris == null)
{
$str .= "<option value='' selected></option>";
}
else
{
$str .= "<option value='999'>Choisir un bris</option>";
}
$i = 0;
while($data = mysql_fetch_assoc($res))
{
if($data['F_BRISID'] == $getBris)
{
$str .= "<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>";
}
else
{
$str .= "<option value='" . $data['F_BRISID'] . "'>" . $data['F_BRISTITLE'] . "</option>";
}
$i++;
}
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
$str .= "</select>";
echo $str;
if(is_numeric($bris))
{
echo "<script type=\"text/javascript\">alert('test');checkSecondValue();</script>";
}
?>
Use your browser's View Source feature to inspect the actual HTML you are generating (which is, in fact, the only see the browser ever sees). It looks like you're inserting random single quotes.
Update:
<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>"
... will render as:
<option value='blah' selected '>blah</option>
It's the only error I've cared to spot but an HTML validator should find them all. Also, I recommend you use this syntax:
<option value="blah" selected="selected">blah</option>
A construct like this
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
is highly wasteful of space and forces you to duplicate a big chunk of html whose only difference is the "selected" attribute. Why not do something like this:
$selected = ($getBris == 12) ? ' selected' : '';
$str .= "<option value=12{$selected}>Autre</option>";

Categories