Need to add the selected attribute to the matching condition. I'm passing the $fetch_state_db as the function parameter which is getting as expected. Please let me know where is the syntax error.
An uncaught Exception was encountered
Type: ParseError
Message: syntax error, unexpected '' value="'' (T_CONSTANT_ENCAPSED_STRING)
$output = '<option value="">Select State</option>';
foreach($query->result() as $row)
{
$output .= '<option '($row->id==$fetch_state_db)?'selected="selected"':''' value="'.$row->id.'">'.$row->region.'</option>';
}
return $output;
Simpler to read and maintain if you dont try and crush everything into the one line. And also if you use " so the variables will auto expand, and use ' quote to wrap the html element attributes.
$output = '<option value="">Select State</option>';
foreach($query->result() as $row) {
$sel = $row->id==$fetch_state_db ? "selected='selected'" : '';
$output .= "<option $sel value='{$row->id}'>{$row->region}</option>";
}
The code should be:
$output .= '<option '. ($row->id==$fetch_state_db)?'selected="selected"':''. ' value="'.$row->id.'">'.$row->region.'</option>';
Easier to read
$output = '<option value="">Select State</option>';
foreach($query->result() as $row)
{
$selected = $row->id== $fetch_state_db ? 'selected="selected"':"" ;
$output .= '<option '.$selected.' value="'.$row->id.'">'.$row->region.'</option>';
}
return $output;
Well it is issue of concatenation. Use the following
output .= '<option '.($row->id==$fetch_state_db ?'selected="selected"':''' ).' value="'.$row->id.'">'.$row->region.'</option>';
}
Sorry i am using mobile.
You have too many single quotes (') in the second part of you ternary.
Try using double quotes instead of single. In my opinion I think it's a little more readable.
foreach($query->result() as $row)
{
$output .= "<option " . ($row->id == $fetch_state_db ? 'selected="selected"' : "") . " value=\"$row->id\">$row->region</option>";
}
return $output;
Related
I am trying to select a previously selected value inside dropdown selection using php. My code is as follows
<?php
$selected_val = "Assistant Professor";
function generateSelect($type = 'text', $name = 'desgntn', $id = 'fac_dsgn', $options = array(), $default) {
$html = '<select type="'.$type.'" name="'.$name.'" id="'.$id.'">';
foreach ($options as $option ) {
if ($option == $default) {
$html .= '<option value='.$option.' selected="selected">'.$option.'</option>';
} else {
$html .= '<option value='.$option.'>'.$option.'</option>';
}
}
$html .= '</select>';
return $html;
}
$list = array("Lecturer", "Assistant Professor", "Associate Professor", "Professor", "Assistant Professor (On Leave)", "Associate Professor (On Leave)", "Professor (On Leave)");
$res = generateSelect('text', 'desgntn', 'fac_dsgn', $list, $selected_val);
echo $res;
?>
But the problem is I am always getting the first word of a multi spaced option inside value attributein option tag of html. for example: I am getting Assistant inside value tag for Assistant Professor. Is there any way so that I can always get the actual value with spaces?
I believe you forgot to enclose the option value in quotes:
it should be something like
$html .= '<option value="'.$option.'" selected="selected">'.$option.'</option>';
(note the double quotes around $option)
Hope it helps
I am trying to set selected on an <option> based on an array, and I'm close, but not quite getting there...
$departments = array("Finance", "IT", "Retail",);
foreach($departments as $list){
echo '<option';
if($found['dept'] == '$list'){ // if I set this manually it works, but not now
echo ' selected';
}
echo ' >' . $list . ' </option>'; // this works fine to show me the list
}
If I set $found[dept] manually like below, echoing 'selected' works great, but I don't want to write a version of this line for every option.
if($found['dept'] == 'Finance'){ echo 'selected';} > ' .$list . '</option>
Your variable is in single quotes which makes it a string. It's cleaner and easier to see errors like that if you break out your logic from your output.
$departments = array("Finance", "IT", "Retail",);
foreach($departments as $list){
$selected = ($found['dept'] == $list) ? ' selected' : '';
echo "<option$selected>$list</option>";
}
I am trying to read a json object using php as follows
$jsonObject = file_get_contents("http://10.12.12.189:9080/NonMotorServices/CommonServices.svc/FetchCurrency");
$jsonres = json_decode($jsonObject, true);
Following are the content of the object
{"Data":"[{\"CurrencySymbol\":\"AU$\",\"CurrencyDescription\":\"Austrailian Dollar\",\"CurrencyRate\":135.42,\"CurrencyType\":\"AUD\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":135.42},{\"CurrencySymbol\":\"£.\",\"CurrencyDescription\":\"British pound sterling\",\"CurrencyRate\":212.62,\"CurrencyType\":\"GBP\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":212.62},{\"CurrencySymbol\":\"EURO\",\"CurrencyDescription\":\"Euro\",\"CurrencyRate\":171.2,\"CurrencyType\":\"EUR\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":171.2},{\"CurrencySymbol\":\"¥.\",\"CurrencyDescription\":\"Japanese yen\",\"CurrencyRate\":1.6809,\"CurrencyType\":\"JPY\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":1.6809},{\"CurrencySymbol\":\"SIN$\",\"CurrencyDescription\":\"Singapore Dollar\",\"CurrencyRate\":107.3,\"CurrencyType\":\"SGD\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":107.3},{\"CurrencySymbol\":\"Rs.\",\"CurrencyDescription\":\"Sri Lankan Rupees\",\"CurrencyRate\":1,\"CurrencyType\":\"LKR\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":1},{\"CurrencySymbol\":\"CHF\",\"CurrencyDescription\":\"Swiss Frank\",\"CurrencyRate\":141.71,\"CurrencyType\":\"CHF\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":141.71},{\"CurrencySymbol\":\"US$.\",\"CurrencyDescription\":\"United States dollar\",\"CurrencyRate\":135,\"CurrencyType\":\"USD\",\"RequestDate\":\"\\\/Date(1408041000000)\\\/\",\"PolicyId\":\"\",\"QuotationId\":0,\"SellingRate\":137}]","ID":1}
I need to list down currency in a html selection and i used following to do so.
echo '<select>';
foreach($jsonres->Data as $option)
{ echo '<option value=' . $option->CurrencyDescription . '>' . $option->CurrencyDescription . '</option>';
}
echo '</select>';
I am getting an empty selection as a result and i need to load 'CurrencyDescription ' as option value. Please help me with this. and please explain what is the error i made because i am new to php and json.
Full Code as follows
<?php
$jsonObject = file_get_contents("http://10.12.12.189:9080/NonMotorServices/CommonServices.svc/FetchCurrency");
$jsonres = json_decode($jsonObject, true);
echo '<select>';
foreach($jsonres->Data as $option)
{ echo '<option value=' . $option->CurrencyDescription . '>' . $option->CurrencyDescription . '</option>';
}
echo '</select>';
?>
$jsonres is actually an array.
This is because true is being passed as the second parameter to json_decode. If you, in fact, do want $jsonres to be an object, then just use json_decode($jsonObject);.
An easy way to check what your variable contains is to use the var_dump function.
$jsonres = json_decode($jsonObject);
var_dump($jsonres);
Also, be sure you have error_reporting turned on and set to E_ALL. The following code, $jsonres->Data, should be causing PHP to emit a "PHP Notice".
Finally I Solve The Problem. Here is My Solution
<select>
<?php
$jsonObject = file_get_contents("http://10.12.12.189:9080/NonMotorServices/CommonServices.svc/FetchCurrency");
$jsonres = json_decode($jsonObject,true);
$val = $jsonres['Data'];
$phpArray = json_decode($val, true);
foreach ($phpArray as $key => $value) {
$curName;
foreach ($value as $k => $v) {
if($k === 'CurrencyDescription'){
$curName=$v;}
}
echo '<option value=' . $curName. '>' . $curName. '</option>';
}
?>
</select>
I have a selectbox with some values, i inserted those values inside an array.
Now i want to select some specific option, and keep the option selected even when the page reloads.
$logos =array('logo1', 'logo2', 'logo3');
echo '
<td class="jofftd">
<label>Platform</label>
<select name="searchpt">
<option value="0">All</option>
';
foreach ($logos as $value)
{
echo '
<option value="'.$value.'">' .$value . '</option>
';
}
echo '
</select>
</td>';
I would need to do something like this:
foreach ($logos as $value)
{
echo '
<option';
if ($value == $value) echo 'selected="selected"';
echo 'value="'.$value.'">' .$value . '</option>
';
}
But it doesn't work.
Thanks.
Assuming you are using a POST method form, the code would look something like this (note: not tested)
foreach ($logos as $value)
{
$selected = ($value == $_POST['searchpt']) ? ' selected' : '';
echo '<option'. $selected . ' value="'.$value.'">' .$value . '</option>';
}
If nothing else, you're missing at least one space character:
<option';
if ($value == $value) echo 'selected="selected"';
This will produce
<optionselected="selected"
which is not exactly valid HTML.
Plus, $value==$value will always be true, so even if you had proper spacing in the tags, you'd be marking ALL of the options as selected. You need to compare the $value from the loop against the value from the original form, e.g.
if ($value == $_POST['field_from_previous_form'}) { ... }
$value == $value will be always true and it will always add selected = "selected"
use string concatenation to form select form field.
<?php
$logos =array('logo1', 'logo2', 'logo3');
$value = 'logo1';
$str = '<select name="searchpt"><option value="0">All</option>';
foreach ($logos as $value)
{
$str.='<option ';
if ($value == 'logo1')
$str.=' selected="selected "';
$str.=' value="'.$value.' ">' .$value . ' </option> ';
}
$str.='</select>';
echo $str;
?>
Hope this code snippet will solve your problem
I`m using this code to repopulate drop down list from the database :
$city_id = 15;
while($row = mysql_fetch_assoc($result)) {
$selected = ($row['city_id'] == $city_id) ? 'selected="selected" ' : NULL;
echo '<option value="'.$city_id .$selected . '">"'.$row['city_name'].'"</option>\n';
}
It`s work like a charm but my question is are they more elegance solutions ?
Other than improving the indentation of the code, this is fine.
$city_id = 15;
while($row = mysql_fetch_assoc($result))
{
$selected = ($row['city_id'] == $city_id) ? ' selected="selected"' : NULL;
echo '<option value="' . $row['city_id']. '"' . $selected . '>'.$row['city_name'].'</option>\n';
}
Well, a more elegant solution would be to have a "controller" file that fetches all the cities an puts them into an array/object list/whatever. Then, in a "view" file, you iterate over that variable. That way, you separate a bit more the presentation from the logic.
In view:
<select name=student value=''>Student Name</option>
<?php foreach($cities as $city): ?>
<option value="<?php echo $city->id ?>" ><?php echo $city->name ?></option>
<?php endforeach; ?>
</select>
Also, I'd highly recommend using PDO for DB access.
I always use a function, since select boxes are something I end up creating a lot...
function select($name, $default, $values, $style='', $param='') {
$html = '<select name="'.$name.'" style="'.$style.'" '.$param.' >';
foreach($values as $i => $data) {
if (isset($data['noFormat'])) {
$html .= '<option value="'.$data['value'].'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.$data['text'].'</option>';
} else {
$html .= '<option value="'.htmlentities($data['value']).'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.htmlentities($data['text']).'</option>';
}
}
$html .= '</select>';
return $html;
}
Then loop through your query to build the array like this:
$default[] = array('value' => '0', 'text' => 'Select a City...');
while($row = mysql_fetch_assoc($result)) {
$list[] = array('value' => $row['city_id'], 'text' => $row['city_name']);
}
$list = array_merge($default,$list);
And finally an example to create the HTML:
select('select','form_el_name',$list['0'],$list,'font-size:12px;','onChange="document.forms[0].submit();"');
Hope it helps!
mysql_fetch_assoc to mysql_fetch_array
add proper comments
use standard php class ezsql or simple class tuts
$query="SELECT name,id FROM student";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[id]>$nt[name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";//Closing of list box