Selected value in a list - php

I'm trying to show the selected value in the list if it's found matching. It's successfully populated but the selected value code does not run.
Code:
$StaffName = 'Jimmy Chan';
<select name="Staff" id="Staff"><?php
$data = array();
$data[0] = '';
echo "<option value='" . $data[0] . "'>" . $data[0] . "</option>";
$result= $DB->query('select No, FirstName, LastName from Staff');
foreach ($result as $data)
{
$SNo = $data['No'];
$SFN = $data['FirstName'];
$SLN = $data['LastName'];
$SName = $SFN.' '.$SLN;
if($SName == $StaffName)
{
echo "<option value='".$Sno."' selected = \"selected\">".$Sname."</option>\n";
}
else
{
echo "<option value='" .$SNo. "'>" . $SName . " </option>";
}
}
?>
</select>
The second else statement do run but not the if statement. I have already put the "selected" inside. Kindly advise.

Try this:
foreach ($result as $data)
{
$SNo = $data['No'];
$SFN = $data['FirstName'];
$SLN = $data['LastName'];
$SName = trim($SFN).' '.trim($SLN);
if(strtolower($SName) == strtolower($StaffName))
{
echo "<option value='".$Sno."' selected = 'selected'>".$Sname."</option>\n";
}
else
{
echo "<option value='" .$SNo. "'>".$SName."</option>\n";
}
}
Also, you have $Sname instead of $SName in first "if" statement. I am not sure if PHP can make a difference on it, but just keep in mind.
The same for $Sno and $SNo variables.

It seems the problem is with the value in variable $SName. Before comparison trim and convert both variables to uppercase or lowercase.
Lower case: http://php.net/manual/en/function.strtolower.php
Uppercase: http://php.net/manual/en/function.strtoupper.php
Trim: http://php.net/manual/en/function.trim.php
Also try,
echo "<option value='".$Sno."' selected="selected">".$Sname."</option>"; //remove \n

You are using
echo "<option value='".$Sno."' selected = \"selected\">".$Sname."</option>\n";
But Variable names are $SNo and $SName and you are using $Sno and $Sname. So Please replace line with line given below.
echo "<option value='".$SNo."' selected = \"selected\">".$SName."</option>\n";
I hope i will be work for you,
thanks

Related

Passing a php variable through from a selector to search database

I'm working on a project for a class and I'm having trouble passing on a variable from a Chosen selector. I am passing on the $inst variable just fine, but the $focus variable is giving me this:
Undefined index: chzn2 in C:\xampp\htdocs\phptest\results.php on line 20.
fyi: I have allowed for null in the database
Here is the code for the selectors.
$sql = "SELECT institutionName, instID FROM institutions";
$dropq = mysqli_query($conn, $sql);
echo "<select data-placeholder='Select an Institution' name='chzn1' class='chzn-select' standard='true' style='width:250px;'>";
while ($row = mysqli_fetch_array($dropq)) {
echo "<option></option><option value='" . $row['instID'] . "'>" . $row['institutionName'] . "</option>";
}
echo "</select>";
$sql1 = "SELECT orgFocus FROM communityOrgs";
$dropq = mysqli_query($conn, $sql1);
echo "<select data-placeholder='Select Focus Area' name='chzn2' class='chzn-select' multiple='true' style='width:250px;'>";
while ($row1 = mysqli_fetch_array($dropq)) {
echo "<option></option>
<option value='" . $row1['orgFocus'] . "'>" . $row1['orgFocus'] . "</option>";
}
echo "</select>";
Here is the code for the results
if (isset($_POST['submit-search'])) {
if(empty($_POST['chzn1']) && empty($_POST['chzn2'])){
echo "Please enter at least one value!";
}
else if(!empty($_POST['chzn1']) || !empty($_POST['chzn2'])) {
// Grabbing variables from User Inputs
$inst = $_POST['chzn1'];
$focus = $_POST['chzn2'];
$query = "SELECT * FROM partnerships WHERE instID = '$inst' OR orgFocus = '$focus'";
$result = mysqli_query($conn, $query);
$queryResults = mysqli_num_rows($result);
if($queryResults > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<div class='results-container'>
<h3>".$row['instName']."</h3>
<p>".$row['orgName']."</p>
<p>".$row['orgFocus']."</p>
</div>";
;}
}
As the error suggests:
Undefined index: chzn2
and according to your logic one out of the two values can be passed that leaves the ability for one to be unset so an error is thrown - as it should.
You need to do a check to see if either one of the $_POST keys exist separately and set their values respectively, either to what was passed or null.
Example
<?php
$chzn1 = null;
$chzn2 = null;
if (!empty($_POST['chzn1']))
$chzn1 = $_POST['chzn1'];
if (!empty($_POST['chzn2']))
$chzn1 = $_POST['chzn2'];
?>
Now they will both have default value so the error won't be thrown.
Note: Seeing as you are using mysqli_* make use of prepared statements.
Update #1
Maybe due to a formatting error but you also have a floating semicolon ;:
;}
Select and option is not separated. As you are echoing separate make it combine.
$row = "<select data-placeholder='Select Focus Area' name='chzn2' class='chzn-select' multiple='true' style='width:250px;'>";
while ($row1 = mysqli_fetch_array($dropq)) {
$row .= "<option></option>
<option value='" . $row1['orgFocus'] . "'>" . $row1['orgFocus'] . "</option>";
}
$row .= "</select>";
echo $row;
Same for other select tag

Retrieve value from DB and display in a drop down on edit form in php

This script does not display the DB value in a drop down on the edit form.
<?php
echo "<select name='assign' value=''><option>Select name</option>";
while ($r = mysql_fetch_array($result)) {
$value = $r['name'];
echo "<option value=" . $r['emp_id'] . ">" . $r['name'] . " if ($name=='$value') echo 'selected = 'selected''></option>";
}
echo "</select>";
It does not show any error. How it can write in a correct way.
You can try this :
$echoSting = '<select name="assign"><option value="">Select name</option>'.PHP_EOL;
while($r = mysql_fetch_array($result)) {
$value=$r['name'];
$echoSting .= '<option value="'.$r['emp_id'].'" '.($name==$value ? 'selected' : '').'>'.$r['name'].'</option>'.PHP_EOL;
}
$echoSting .= '</select>'.PHP_EOL;
echo $echoSting;
a side note, try looking into PDO for your database stuff : http://php.net/manual/en/book.pdo.php
Try this:
echo "<select name='assign' value=''><option>Select name</option>";
while($r = mysql_fetch_array($result)) {
$value=$r['name'];
echo "<option value='.$r['emp_id'].'>'.$r['name'].' "; if ($name=='$value') echo "selected = 'selected'";echo">$value</option>";
}
echo "</select>";

Populate multi-select with php while loop from db

The following worked on a local environment. Now that it's pushed
live everything but these seems to work. Displays completely empty select boxes now no checks or blank labels just empty space in the "select options" drop down.
select display
<?php
$selected = array();
$selected = explode(",",$fill['markets']);
$condb = mysql_query("SELECT * FROM `countries`");
$count = mysql_num_rows($condb);
$countries = array();
$str;
while ($countries = mysql_fetch_array($condb))
{
$str = "option{$countries['id']}";
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
}
?>
You should use while loop instead. You can declare $i outside the loop if you need it, Try the following code:
$condb = mysql_query("SELECT * FROM `countries`");
$i = 0;
while($countries = mysql_fetch_array($condb)) {
$str = 'option' . $i;
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
$i++;
}
?>
</select>
Note:
mysql_* is deprecated as of php-5.5. So instead use mysqli_* or PDO.
Why shouldn't I use mysql_* functions in PHP?

Populating select input field with value from mysql

My form has input fields with values populated from mysql table. In my select statement I am passing these values to the fields. The table is called person and has a unique id person_id and foreign key academy_id. Each person has a status active or inactive stored in field name person_status. I am having difficulties pulling the values from person_status for each person. How would I show the status for each person inside the select query? EXAMPLE
Select query to populate
<?php
$id = 15;
$db_select2 = $db_con->prepare("
SELECT a.name,
a.academy_id,
p.person_id,
p.person_status,
p.first_name
FROM academy a
LEFT JOIN person p ON a.academy_id = p.academy_id
WHERE a.academy_id = :id
");
if (!$db_select2) return false;
if (!$db_select2->execute(array(':id' => $id))) return false;
$results2 = $db_select2->fetchAll(\PDO::FETCH_ASSOC);
if (empty($results2)) return false;
$result2 = '';
$s = 1;
echo "<table>";
echo "<tbody>";
foreach ($results2 as $value2){
echo "<tr>";
echo "<td>Name #".$s."<input type=\"hidden\" name=\"person_id_".$s."\" value='". $person_id = $value2['person_id']."' readonly=\"readonly\"/><input id=\"person_fname_".$s."\" name=\"person_fname_".$s."\" placeholder=\"Person #".$s." First Name\" type=\"text\" value='" . $value2['first_name'] ."'/></td>";
echo "</tr>";
$s++;
}
echo "</tbody>";
echo "</table>";
?>
would like to integrate this to select statement:
<?php
$table_name2 = "person";
$column_name2 = "person_status";
echo "<select name=\"$column_name2\"><option>Select one</option>";
$sql1 = 'SHOW COLUMNS FROM '.$table_name2.' WHERE field="'.$column_name2.'"';
$row1 = $db_con->query($sql1)->fetch(PDO::FETCH_ASSOC);
$selected1 = '';
foreach(explode("','",substr($row1['Type'],6,-2)) as $option) {
if ($status == $option){
$selected1 = "selected=selected";
}else{
$selected1='';
}
echo "<option value='$option'" . $selected1. ">$option</option>";
}
echo "</select></br>";
?>
Get options only once (no need to repeat this for every person):
$sqlStatuses = 'SHOW COLUMNS FROM '.$table_name2.' WHERE field="'.$column_name2.'"';
$rowStatuses = $db_con->query($sql1)->fetch(PDO::FETCH_ASSOC);
$personStatuses = explode("','",substr($rowStatuses['Type'],6,-2));
Then, walk over the persons
foreach ($results2 as $value2) {
// Your code
echo "<tr>";
echo "<td>Name #".$s."<input type=\"hidden\" name=\"person_id_".$s."\" value='". $person_id = $value2['person_id']."' readonly=\"readonly\"/><input id=\"person_fname_".$s."\" name=\"person_fname_".$s."\" placeholder=\"Person #".$s." First Name\" type=\"text\" value='" . $value2['first_name'] ."'/></td>";
// Added
echo '<td><select name="person_status_'.$s.'">';
foreach($personStatuses as $option) {
echo '<option value="'.htmlspecialchars($option).'" ';
if ($value2['person_status'] == $option) {
echo 'selected="selected"';
}
echo '>' . htmlspecialchars($option) . '</option>';
}
echo '</select></td>';
// Your code again
echo "</tr>";
$s++;
}
Building this into one SELECT-query is unneccessary complex (although possible, but gives you unreadable code).
Oh, and take a look at htmlspecialchars(), if a name contains a "-character your HTML get screwed up

Php: Set default drop down value in a loop

A drop down list is printed in php in a while loop by taking value from database table. Here is the code:
<select name='supervisor' class='form-control' name='supervisor'>
<?php
$sql = "SELECT username FROM system_user where type='supervisor'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";}?>
</select>
How can I set a default value for this? There is one 'username' value that i want to make as the default value. How can i do that?
<select name='supervisor' class='form-control' name='supervisor'>
<?php
$sql = "SELECT username FROM system_user where type='supervisor'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$sel = ''; if($row['username'] == 'usename'){ $sel = 'selected'; }
echo "<option $sel value='" . $row['username'] ."'>" . $row['username'] ."</option>";
} ?>
</select>
function dropDown(array $array, $default = null, $select_attrs = '')
{
$s = '<select $select_attr>';
foreach((array)$array as $k => &$v) {
$default = ($v === $default) ? 'selected' : null;
$s.='<option '.$default.' >'.$v.'</option>';
}
return $s;
}
this one worked for me...
<select name='supervisor' class='form-control' name='supervisor'>
<?php
$sql = "SELECT username FROM system_user where type='supervisor'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$sel = ''; if($row['username'] == 'usename'){ $sel = 'selected'; }
echo "<option $sel value='" . $row['username'] ."'>" . $row['username'] ."</option>";
} ?>

Categories