I am struggling to get this code to work, what I want from it is to show the item (that is already in the database) to be selected in the selection form.
<label>Server Ports:</label>
<select multiple class="form-control" name="select[]">
<?php
// Get Server Information
$query = "SELECT port_no FROM _servers WHERE (server_id = '$servid') ";
$result = mysql_query($query) or die ('Unable to run query:'.mysql_error());
while($row = mysql_fetch_assoc($result)){
$no = $row['port_no'];
}
$query = "SELECT id, name, port_no, unique_id FROM ports ORDER BY name ASC";
$result = mysql_query($query) or die ('Unable to run query:'.mysql_error());
while($row = mysql_fetch_assoc($result))
{
$port_no = $row['port_no'];
$port_name = $row['name'];
$p_unique = $row['unique_id'];
}
?>
<option value="<?php echo $p_unique;?>"
<?php
if ($p_unique == $no) {
$check = 'selected';
} else {
$check = '';
}
echo $check;
?>
>
<?php
echo $row['name'];
?>
(
<?php
echo $row['port_no'];
?>
)</option>
<?php
}
?>
</select>
Are you sure your test must be if ($p_unique == $no) {} and not if ($port_no == $no) {} ?
If yes, try to checks your variables values :
Do a var_dump() of $no :
var_dump($no);
In your while() loop, you can also check values of $p_unique and $no like that :
var_dump($p_unique.'/'.$no);
Also, here is a simplest way to test for selected :
<option value="<?php echo $p_unique;?>" <?php if ($p_unique == $no) echo 'selected="selected"'; ?>><?php echo $row['name'] ;?> (<?php echo $row['port_no'] ;?>)</option>
Related
I have this non-dynamic script works like this:
<p>Environment: <select name="formEnvironment" value="" >
<option value="TEST" <?= $_POST['formEnvironment'] == TEST ? 'selected' : '' ?>>Test</option>
<option value="PROD" <?= $_POST['formEnvironment'] == PROD ? 'selected' : '' ?>>Production</option>
</select></p>
As I have tried to make it more dynamic as possible within variables. I have problems with code within while nest and I do think it has to do with strings and variables mixing together which makes it more complicated. Any assistance with what is right way to code in that regard. I would appreciate assistance as I am only few months into PHP.
function DropDownItems($itemName, $query, $connection)
{
$result = mysqli_query($connection, $query);
while ($row = $result->fetch_assoc()){
$MAS = "$_POST['form"{$itemName}"']";
echo "<option value=\"{$row['DDVALUE']}\" ";
echo "<?= "{$MAS}" == "{$row['DDVALUE']}" ? 'selected' : '' ?>>"{$row['DDTEXT']}"</option>";
}
}
$itemName="Environment";
$query = "SELECT DDVALUE, DDTEXT FROM DDLISTS WHERE FIELDNAME='".$itemName."' ORDER BY DDTEXT ASC";
echo "<p>$itemName.": <select name='form".$itemName."'>";
echo "<option value=''>Select below:</option>";
DropDownItems($itemName, $query, $connection);
echo "</select>";
Its never a good idea to echo in functions, instead just return an array and then loop over it.
You can also break out of PHP so you don't need to do lots of echos.
So many syntax errors, so I've just rewrote it:
<?php
function DropDownItems($itemName, $query, $connection) {
$return = [];
$result = mysqli_query($connection, $query);
while ($row = $result->fetch_assoc()) {
$return[] = [
'value' => $row['DDVALUE'],
'label' => $row['DDTEXT']
];
}
return $return;
}
$itemName="Environment";
$query = "SELECT DDVALUE, DDTEXT FROM DDLISTS WHERE FIELDNAME='".$itemName."' ORDER BY DDTEXT ASC";
?>
<p><?= $itemName ?>
<select name="form<?= $itemName ?>">
<option value="">Select below:</option>
<?php foreach (DropDownItems($itemName, $query, $connection) as $item): ?>
<option value="<?= $item['value'] ?>"<?= (isset($_POST['form'.$itemName]) && $_POST['form'.$itemName] === $item['value'] ? ' selected' : '') ?>><?= $item['label'] ?></option>
<?php endforeach ?>
</select>
</p>
Be aware of SQL injections, if $itemName="Environment"; is user supplied you should change the code to use prepared queries.
Fixed the syntax errors. And made the code a little more readable. You can try the below code. Haven't tested it, hope it works fine.
<?php
function DropDownItems($itemName, $query, $connection)
{
$result = mysqli_query($connection, $query);
$html = '';
while ($row = $result->fetch_assoc()){
$MAS = $_POST['form'.$itemName];
$html .= "<option value=\"{$row['DDVALUE']}\" ";
$html .= ( $MAS == $row['DDVALUE'] ? 'selected' : '' ).">{$row['DDTEXT']}</option>";
}
return $html;
}
$itemName="Environment";
$query = "SELECT DDVALUE, DDTEXT FROM DDLISTS WHERE FIELDNAME='".$itemName."' ORDER BY DDTEXT ASC";
echo "<p>$itemName".": <select name='form".$itemName."'>";
echo "<option value=''>Select below:</option>";
echo DropDownItems($itemName, $query, $connection);
echo "</select>";
?>
<div class="select_list">
<div class="labels">Category:</div>
<?php
if(!isset($_POST['postbtn)){
echo "<script>$(document).ready(function(){
$('.category').val(0);
})
</script>";
}
echo "<select name='category' id='catg_list' class='list_catg'>
<option value='0'";
if(isset($_POST['category']) && $_POST['category']=='0'){
echo "selected";
}
echo">none</option>";
$query = mysql_query("SELECT id, name from table1");
while($query_fetch = mysql_fetch_assoc($query)){
echo "<option value='".$query_fetch['id']."'";
if(isset($_POST['category']) && $_POST['category']==$query_fetch['id'])
{
echo "selected";
}
echo ">".$query_fetch['name']."</option>";
}
echo "</select>";
?>
</div>
The problem with the above code is that the selected element stays selected after the submission is done. I need the select option to return back to 'none' when the form is submitted successfully. How can that be done?
You have an syntax error in your line:
if(!isset($_POST['postbtn)){
change it to:
if(!isset($_POST['postbtn'])){
I'm guessing some things you didn't mention:
You validate your script above the code you posted, and you want - if the script was validated successfully - that the "none" option is selected.
$selected_value = $validation ? $_POST['category'] : false;
Only if the Validation is correct the value will be set, else it will be set to false;
<?php
echo "<select name='category' id='catg_list' class='list_catg'>
<option value='0'";
//CHANGE
if($selected_value == 0){ //Or if($selected_value === FALSE ||$selected_value === 0)
echo "selected";
}
echo">none</option>";
$query = mysql_query("SELECT id, name from table1");
while($query_fetch = mysql_fetch_assoc($query)){
echo "<option value='".$query_fetch['id']."'";
//CHANGE
if($selected_value !== FALSE && $selected_value == $query_fetch['id'])
{
echo "selected";
}
echo ">".$query_fetch['name']."</option>";
}
echo "</select>";
?>
Simplify your code as following to do required task.
$category = isset($_POST['category']) ? $_POST['category'] : 0;
$array["0"]="none";
$query = mysql_query("SELECT id, name from table1");
while($query_fetch = mysql_fetch_assoc($query)){
$id = $query_fetch['id'];
$array[$id] = $query_fetch['name'];
}
echo "<select name='category' id='catg_list' class='list_catg'>";
foreach($array as $id=>$name) {
$selected = $category==$id ? "selected" : "";
echo "<option value='".$id."' ".$selected." >".$name."</option>";
}
echo "</select>";
I have a script that get all ids from a table and print them on option select form, and i want to reload page with the id i chose as selected on option. This is the script:
<?php
include('include/menu.php');
include('include/mysql.php');
if ($db_found) {
echo "<form action='' name='form' method ='get'>
<select name='funcionario'>";
$SQL = "SELECT * FROM funcionarios";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
$idfunc = $_GET['funcionario'];
$selected = ($idfunc==$idfunc->$db_field['idfunc']) ? ' selected="selected"' : '';
echo "<option value'".$db_field['idfunc']."' ".$select." onclick='document.form.submit();' >".$db_field['nomefunc']."</option>";
}
echo "</selected></form>";
echo $idfunc;
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
But the script are always returning only the first id as selected.
Remove $idfunc-> from $idfunc->$db_field['idfunc']
Replace value'".$db_field['idfunc']."' with value='".$db_field['idfunc']."'
You already defined $idfunc = $_GET['functionario'] which is a string, not an class object.
Also you defined $selected but you are using $select when echoing the result.
For further debugging, use error_reporting(E_ALL); at the top of your script. I guess that's why you didn't get error when you tried to execute this script.
Here's complete script:
<?php
include('include/menu.php');
include('include/mysql.php');
if ($db_found) {
echo "<form action='' name='form' method ='get'>
<select name='funcionario'>";
$SQL = "SELECT * FROM funcionarios";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
$idfunc = $_GET['funcionario'];
$selected = ($idfunc==$db_field['idfunc']) ? ' selected="selected"' : '';
echo "<option value='".$db_field['idfunc']."' $selected onclick='document.form.submit();'>".$db_field['nomefunc']."</option>";
}
echo "</selected></form>";
echo $idfunc;
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
$selected = ($idfunc)==$db_field['idfunc'] ? ' selected="selected"' : '';
echo "<option value'".$db_field['idfunc']."' ".$selected." onclick='document.form.submit();' >".$db_field['nomefunc']."</option>";
I hope this is you want! Try this!
I am new to php, i created drop down which calling data from mysql data base, user selects option and its save to data base.
Problem Arises in edit form in which its do not showing selected value.
Drop Down code is below:
$query = 'SELECT name FROM owner';
$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
//create selection list
echo "<select name='owner'>\name";
while($row = mysql_fetch_row($result))
{
$heading = $row[0];
echo "<option value='$heading'>$heading\n";
}
echo "</select>"
Please advise solution for the edit form.
Thanks in Advance
you must close <option> tag:
echo "<option value='$heading'>$heading</option>";
$query = 'SELECT name FROM owner';
$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
//create selection list
echo "<select name='owner'>\name";
while($row = mysql_fetch_row($result))
{
$heading = $row[0];
?>
<option <?php if($heading=="SOMETHING") { echo "selected='selected'"; } ?> value="SOMETHING">SOMETHING</option>
<option <?php if($heading=="SOMETHING2") { echo "selected='selected'"; } ?> value="SOMETHING2">SOMETHING2</option>
<option <?php if($heading=="SOMETHING3") { echo "selected='selected'"; } ?> value="SOMETHING3">SOMETHING3</option>
<?php
}
echo "</select>"
I'd do it this way.
$numrows = mysql_num_rows($result);
if ($numrows != 0){
echo "<select name='owner'>\name";
while ($x = mysql_fetch_assoc($result)){
echo "<option value='".$x['heading']."'>".$x['heading']."</option>";
}
echo "</select>";
}
$x['heading'] is using the value of the row 'heading' in the database
It's much more efficient and simply looks more sophisticated.
If in the browser I have parameters like:
http://localhost/specials.php?year=2009&make=honda&model=civic
and the dropdown looks something like this:
<select name="year">
<?php
$query = mysql_query("select distinct year from tbl_content where year = '$year'");
while($row = mysql_fetch_assoc($query)) {
echo "<option value=\"{$row['year']}\">{$row['year']}</option>";
}
?>
</select>
Now what I'm trying to do is show select when the dropdown options value is equal to the parameter year in the browser URL.
I tried this:
<select name="year">
<?php
$query = mysql_query("select * from tbl_year
while($row = mysql_fetch_assoc($query)) {
#=============================
if(isset($_GET['year'])) {
$year = (int)$_GET['year'];
if($year == $row['year'] { $selected = "selected"; }
else { $selected = "";
}
echo "<option value=\"{$row['year']}\" {$selected}>{$row['year']}</option>";
}
?>
</select>
Maybe try "selected='selected'" to make it valid xml.
<select name="year">
<?php
$selectedYear = NULL;
if(isset($_GET['year']))
$selectedYear = (int)$_GET['year'];
$query = mysql_query('SELECT year FROM tbl_year GROUP BY year ORDER BY year ASC');
while($row = mysql_fetch_assoc($query)) {
echo '<option value="' . htmlspecialchars($row['year']) . '"';
if($selectedYear === (int)$row['year']) {
echo ' selected="selected"';
}
echo '>' . htmlspecialchars($row['year']) . '</option>";
}
?>
</select>
Fell free to separate functionality!
<?php
function selectList($name,$values,$labels=null,$selected=null){
if($labels==null) $labels=&$values;
$data="<select name='$name'>";
foreach($values as $k=>$v){
$selected=($v==$selected)?'selected="selected"':false;
$data.="<option value='$v' $selected>".htmlspecialchars($labels[$k])."</option>";
}
$data.="</select>";
return $data;
}
$select=isset($_REQUEST['year'])?(int) $_REQUEST['year']:null;
$query=mysql_query("SELECT DISTINCT `year` FROM `tbl_year` ORDER BY `year`");
while(($row=mysql_fetch_assoc($query))!==false){
$values[]=$row['year'];
}
echo selectList("year",$values,null,$select);
?>