How to echo selected in options list looping? - php

I want to presist (=keep values if error on form) my values from a dropdown menu , this is what i started with :
...
$priorities = array('low','normal','high');
...
<select name="priority" id="priority">
<?php
foreach ($priorities as $pro){
echo '<option value="'.$pro.'">'.$pro.'</option>';
}
?>
</select>
It does the job but does not presist.
Now i want to get to something like this :
<select name="priority" id="priority">
<?php
$tel = 0;
foreach ($priorities as $pro){
echo '<option value="'.$tel.'"'.htmlentities('<?php if (isset($_POST[\'priority\']) && (int) $_POST[\'priority\'] === tel) { echo \'selected="selected"\'; } ?>').' >'.$pro.'</option>';
$tel++;
}
?>
</select>
But that of course gives an error.
Anyone has any suggestions thx

Here's how I often implement this:
<select name="priority" id="priority">
<?php
foreach ($priorities as $pro)
{
$selected = (isset($_POST['priorities']) && $pro == $_POST['priority']) ? 'selected' : '';
echo '<option value="' . $pro . '" '.$selected.'>' . $pro . '</option>';
}
?>
</select>
Just thought I'd point out you can actually shorten the ternary here like so
<select name="priority" id="priority">
<?php
foreach ($priorities as $pro)
{
$selected = ($pro == #$_POST['priority']) ? 'selected' : '';
echo '<option value="' . $pro . '" '.$selected.'>' . $pro . '</option>';
}
?>
</select>
Sorry I've got a bit of a thing for creating the shortest code possible :)

Change the second part of the code to:
<select name="priority" id="priority">
<?php
foreach ($priorities as $pro) {
if (isset($_POST['priority']) && $_POST['priority'] == $pro) {
$selected = 'selected="selected"';
}
else {
$selected = null;
}
echo '<option value="'.$pro.'" '.$selected.'>'.$pro.'</option>';
}
?>
</select>

Try this
<select name="priority" id="priority">
<?php
$tel = 0;
foreach ($priorities as $pro){
echo '<option value="'
.$tel
.'"'
.(isset($_POST['priority']) && (int)$_POST['priority'] === $tel)?'selected="selected"':''
.' >'
.$pro
.'</option>';
$tel++;
}
?>
</select>

$priority= array (1=>"low","normal","high");
$select = "<select name=\"priority\"> ;
foreach ($priority as $key => $val) {
$select .= "\t<option val=\"".$key."\"";
if ($val == $yourcheckedvariable) {
$select .= " selected=\"selected\">".$val."</option>\n";
} else {
$select .= ">".$val."</option>\n";
}
}
$select .= "</select>";
echo $select;
use this code

Related

How to do Multiple select option using php?

I like do multiple select option using PHP , but i am unable to do multiple select.
this is my code
<?
include_once("common.php");
$iCompanyId = isset($_REQUEST['company'])?$_REQUEST['company']:'';
$iDriverId = isset($_REQUEST['iDriverId'])?$_REQUEST['iDriverId']:'';
$selected = "selected";
if($iCompanyId != '')
{
$sql = "select * from register_driver where iCompanyId = '".$iCompanyId."' and eStatus != 'Deleted'";
$db_model = $obj->MySQLSelect($sql);
$cont = '';
$cont .= '<select multiple class="validate[required] form-control" id="iDriverId1" name="iDriverId">';
$cont .= '<option value="">CHOOSE DRIVER </option>';
for($i=0;$i<count($db_model);$i++){
if($db_model[$i]['iDriverId'] == $iDriverId)
$cont .= '<option value="'.$db_model[$i]['iDriverId'].'" '.$selected.'>'.$db_model[$i]['vName'].' '.$db_model[$i]['vLastName'].'</option>';
else
$cont .= '<option value="'.$db_model[$i]['iDriverId'].'">'.$db_model[$i]['vName'].' '.$db_model[$i]['vLastName'].'</option>';
}
$cont .= '</select>';
echo $cont; exit;
}
?>
Use 'selected Attribute' like
if(condition) { <option value="" selected> test</option>

how to keep selected item in selectbox after page refreshing in PHP

I have made many select box in PHP and I want to keep selected item as selected after refreshing the page. (when selecting same select box or another) here is my code.
$selectbox='<select class="form-control" name="estate_id" onchange="this.form.submit()" style="width: 200px" >';
$est_name = $client ->call('get_estate'); // call method from web services
$_SESSION['estname'] = array();
$_SESSION['estname'] = $est_name;
$count = count($_SESSION['estname']);
$i = 0;
foreach ($_SESSION['estname'] as $row)
{
$id = $_SESSION['estname'][$i]['est_id'];
$name = $_SESSION['estname'][$i]['est_name'];
if($id == isset($_POST['estate_id']))
{
$isSelected = ' selected="selected"';
}
else {
$isSelected = '';
}
$selectbox.= "<option value=".$id.$isSelected.">".$name."</option>";
$i++;
}
$selectbox.='</select>';
echo $selectbox;
<select name="name">
<option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
<option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>

php use 1 sql statement

How can I make my queries short?
I have the same query multiple times on my page on different sections.
Here's the code to see what I mean:
//sql for dropdown contact type
$sql_getContactType1 = $db->query('SELECT * FROM tb_phone_contact_type');
$sql_getContactType2 = $db->query('SELECT * FROM tb_phone_contact_type');
$sql_getContactType3 = $db->query('SELECT * FROM tb_phone_contact_type');
Output in dropdown:
<select name="contact_type1" class="form-control">
<?php
while($row = $sql_getContactType1->fetch_assoc())
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
</select>
<select name="contact_type2" class="form-control">
<?php
while($row = $sql_getContactType2->fetch_assoc())
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
<select name="contact_type3" class="form-control">
<?php
while($row = $sql_getContactType3->fetch_assoc())
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
</select>
How can I achieve it in just one query statement on my output?
Do the query once, put the results in an array, and then use that array in each <select>.
<?php
$sql_getContactType = $db->query('SELECT id, name FROM tb_phone_contact_type');
$contact_types = array();
while ($row = $sql_getContactType->fetch_assoc()) {
$contact_types[] = $row;
}
?>
<select name="contact_type1" class="form-control">
<?php
foreach($contact_types as $row)
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
</select>
<select name="contact_type2" class="form-control">
<?php
foreach($contact_types as $row)
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
<select name="contact_type3" class="form-control">
<?php
foreach($contact_types as $row)
{
echo '<option value="'.$row[id].'">'.$row[d_name] . '</option>';
}
?>
</select>
Why using 3 select? u can use one they do same job.
For selects you must use foreach.
First, get all data in a single query. Then you can add if inside your loop to determine the contact type to show. This example code may help you:
$contacts = $db->query('SELECT * FROM tb_phone_contact_type')->fetch_assoc();
<select name="contact_type1" class="form-control">
<?php
foreach ($contacts as $contact) {
// fit this code by the `type` you want to show
if ($contact['type'] === 'CONTACT_TYPE_1') {
echo '<option value="'.$contact['id'].'">'.$contact['d_name'].'</option>';
}
}
?>
</select>
<select name="contact_type2" class="form-control">
<?php
foreach ($contacts as $contact) {
// fit this code by the `type` you want to show
if ($contact['type'] === 'CONTACT_TYPE_2') {
echo '<option value="'.$contact['id'].'">'.$contact['d_name'].'</option>';
}
}
?>
<select name="contact_type3" class="form-control">
<?php
foreach ($contacts as $contact) {
// fit this code by the `type` you want to show
if ($contact['type'] === 'CONTACT_TYPE_3') {
echo '<option value="'.$contact['id'].'">'.$contact['d_name'].'</option>';
}
}
?>
</select>
Execute query and store data into array... You can use array multiple times..
$sql_getContactType1 = $db->query('SELECT * FROM tb_phone_contact_type');
while($row = $sql_getContactType1->fetch_assoc())
{
$row_info[] = $row;
}
foreach ($row_info as $info) {
echo "Id: {$info[id]}<br />"
. "Name: {$info[name]}<br />"
. "Code: {$info[code]}<br /><br />";
}
SQL for dropdown contact type
<?php
$sql_getContactType1 = $db->query('SELECT * FROM tb_phone_contact_type');
while($row = $sql_getContactType1->fetch_assoc())
{
$row_data[] = $row;
}
?>
Output in dropdown :
<select name="contact_type1" class="form-control">
<?php
foreach($row_data as $row_val)
{
echo '<option value="'.$row_val[id].'">'.$row_val[d_name] . '</option>';
}
?>
</select>
<select name="contact_type2" class="form-control">
<?php
foreach($row_data as $row_val)
{
echo '<option value="'.$row_val[id].'">'.$row_val[d_name] . '</option>';
}
?>
<select name="contact_type3" class="form-control">
<?php
foreach($row_data as $row_val)
{
echo '<option value="'.$row_val[id].'">'.$row_val[d_name] . '</option>';
}
?>
</select>
Use above the code if you need 3 dropdown on a page.

How to embed if statement inside echo [duplicate]

This question already has answers here:
if block inside echo statement?
(4 answers)
Closed 11 months ago.
I'm gettin' a headache on that. I need to put if statement inside an echo (this echo is in a function, it's for a form submit actually)
Here is an example on a partial of my code. In this situation, how can I put theses if statement inside my echo??
<?php echo '<td><select id="depuis" name="depuis">
<option value=\'4\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'4\'){ echo \'selected\'; } else { echo ''; } ?> ></option>
<option value=\'1\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'1\'){ echo \'selected\'; } else { echo ''; } ?> >2 ans et moins</option>
<option value=\'2\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'2\'){ echo \'selected\'; } else { echo ''; } ?> >2 à 5 ans</option>
<option value=\'3\' <?php if(isset($_POST[\'depuis\']) && $_POST[\'depuis\'] == \'3\'){ echo \'selected\'; } else { echo ''; } ?> >5 ans et plus</option>
</select>
</td>'
; ?>
Everything is php so need to use more than the first <?php Finish each echo before checking with if. Like this:
<?php
echo '<td><select id="depuis" name="depuis">
<option value="4"';
if(isset($_POST['depuis']) && $_POST['depuis'] == '4') {
echo ' selected';
}
echo ' >Something here maybe?</option>...etc
Use an inline if statement:
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody');
This would work - although I'm sure it could be streamlined:
<?php
$out = '
<td>
<select id="depuis" name="depuis">
<option value="4"
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '4'){
$out .= 'selected';
}
$out .= '
></option>
<option value='1'
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '1'){
$out .= 'selected';
}
$out .= '
>2 ans et moins</option>
<option value=\'2\'
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '2'){
$out .= 'selected';
}
$out .= '
>2 à 5 ans</option>
<option value='3'
';
if(isset($_POST['depuis']) && $_POST['depuis'] == '3'){
$out .= 'selected';
}
$out .= '
>5 ans et plus</option>
</select>
</td>
';
echo $out;
?>
Meilleurs voeux...
You will want to use the a ternary operator which acts as a shortened IF/Else statement:
echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';
You shouldn't escape the array keys in the string
if(isset($_POST[\'depuis\']) ...
Should be
if(isset($_POST['depuis']) && ...
Also you could clean up the the generation of the options with a array and a loop
$options = array(
'label1' => 1,
'label2' => 2,
'label3' => 3,
'label4' => 4
);
$value = (isset($_POST['depuis'])) ? $_POST['depuis'] : 0;
foreach ($options as $label => $optionValue) {
$selected = ($optionValue == $value) ? ' selected' : '';
printf('<option value="%s"%s>%s</option>', $optionValue, $selected, $label);
}
Not sure you can do that like you're asking. You'd just need to use regular if/else if block and output the outcome separately.
<?php
echo("<td><select id=\"depuis\" name=\"depuis\">");
echo("<option value='4'");
if(isset($_POST['depuis']) && $_POST['depuis'] == '4'){ echo("selected"); }
echo("></option>");
[ ...etc... ]
?>

PHP + form select options

I have a select that looks like this, it is written in in HTML and is not rendered via any php,
<select name="position">
<option value="left">Left</option>
<option value="right">Right</option>
<option value="centre">Centre</option>
</select>
The value gets sent to database and later on gets returned from the database as a variable in the form of $v['position'], using this and my original form how can I make the option that matches the varibale the default selection?
You didn't specify when the form displayed again.
If immediately when user is submitted the form, you need to insert this snippet to every option:
<option value="left"<?php echo $v['position'] == 'left' ? ' selected' : ''; ?>>Left</option>
<option value="right"<?php echo $v['position'] == 'right' ? ' selected' : ''; ?>>Right</option>
<option value="centre"<?php echo $v['position'] == 'centre' ? ' selected' : ''; ?>>Centre</option>
OR:
You must iterate through variables via PHP :(
$html = '<select name="position">';
$opts = array('left', 'right', 'centre');
foreach($opts as $option)
{
$html .= '<option value="' . $option . '"';
$html .= $option == $v['position'] . ' selected' : '';
$html .= '>' . ucfirst($option) . '</option>';
}
$html .= '</select>';
print $html;
You can create the options in a loop and check whether the current element equals the value in $v['position'] and set the selected attribute accordingly.
<?php
$options = array('left'=>'Left', 'right'=>'Right', 'centre'=>'Centre');
?>
<select name="position">
<?php foreach($options as $value=>$text):?>
<option value="<?php echo $value ?>"
<?php echo ($v['position'] == $value) ? 'selected="selected"' : '' ?> >
<?php echo $text ?>
</option>
<?php endforeach; ?>
</select>
You can do it with DOM without having to touch your HTML. If this is your HTML:
$template = <<< TPL
<select name="position">
<option value="left">Left</option>
<option value="right">Right</option>
<option value="centre">Centre</option>
</select>
TPL;
And this is the value that was selected:
$value = 'right';
You can do
$dom = new DOMDocument;
$dom->loadXml($template);
$xPath = new DOMXPath($dom);
$node = $xPath->query(sprintf('//option[#value = "%s"]', $value));
if($node->item(0)) {
$node->item(0)->setAttribute('selected', 'selected');
}
echo $dom->saveXML($dom->documentElement);
And that will output:
<select name="position">
<option value="left">Left</option>
<option value="right" selected="selected">Right</option>
<option value="centre">Centre</option>
</select>
try this
<select name="position">
<option value="left" <?php echo $v['position']=='left'?'selected="selected"':'' ?> >Left</option>
<option value="right" <?php echo $v['position']=='right'?'selected="selected"':'' ?>>Right</option>
<option value="centre" <?php echo $v['position']=='centre'?'selected="selected"'?:'' >>Centre</option>
</select>
<select name="position">
<option value="left"<?php echo ($v['position'] == 'left') ? ' selected="selected" : ''; ?>>Left</option>
<option value="right"<?php echo ($v['position'] == 'right') ? ' selected="selected" : ''; ?>>Right</option>
<option value="centre"<?php echo ($v['position'] == 'centre') ? ' selected="selected" : ''; ?>>Centre</option>
</select>

Categories