Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am coding a PC repair application using MySQLi. I have an ENUM row in my database called "item_for_repair". In the ENUM list is Laptop, Desktop etc etc.
On my front end html table, when i click edit on a specific job card, under "item for repair" there is a drop down that always has the first value (for example, Laptop) selected and not the actual item that was stored (for example, Desktop), i need the drop down to be pre-selected with the item for repair that was originally stored in the database when storing the job card.
Here is an example image of what is happening. The item for repair in the databse is Desktop, but here you can clearly see its showing Laptop.
My code to connect to database as well as select all from the database:
<?php include 'settings.php'; //This file has all the database connection settings etc.
?>
<?php
$eid=$_GET['editid'];
$ret=mysqli_query($conn,"select * from pcrepairs where job_number='$eid'");
while ($row=mysqli_fetch_array($ret)) {
?>
And here is the select box code:
<select name="item_for_repair" id="item_for_repair">
<option value="Laptop" <?= $item_for_repair === 'Laptop' ? 'selected' : '' ?>>Laptop</option>
<option value="Desktop" <?= $item_for_repair === 'Desktop' ? 'selected' : '' ?>>Desktop</option>
<option value="Television" <?= $item_for_repair === 'Television' ? 'selected' : '' ?>>Television</option>
<option value="Washing Machine" <?= $item_for_repair === 'Washing Machine' ? 'selected' : '' ?>>Washing Machine</option>
<option value="Tumble Dryer" <?= $item_for_repair === 'Tumble Dryer' ? 'selected' : '' ?>>Tumble Dryer</option>
<option value="Dishwasher" <?= $item_for_repair === 'Dishwasher' ? 'selected' : '' ?>>Dishwasher</option>
<option value="Microwave" <?= $item_for_repair === 'Microwave' ? 'selected' : '' ?>>Microwave</option>
<option value="Fridge" <?= $item_for_repair === 'Fridge' ? 'selected' : '' ?>>Fridge</option>
<option value="Printer" <?= $item_for_repair === 'Printer' ? 'selected' : '' ?>>Printer</option>
<option value="Other" <?= $item_for_repair === 'Other' ? 'selected' : '' ?>>Other</option>
</select>
Where have i gone wrong?
Here is a complete example of how to populate an HTML select retrieving data from a MySQL database using MySQLi
<?php
class Country {
public $code;
public $name;
function __construct($code, $name) {
$this->code = $code;
$this->name = $name;
}
}
define("HOST", "localhost");
define("USERNAME", "root");
define("PASSWD", "");
define("DBNAME", "shop");
function country_select_list() {
$array = null;
$link = mysqli_connect(HOST, USERNAME, PASSWD, DBNAME);
$stmt = mysqli_prepare($link, "select code, name from country order by name");
if (!mysqli_execute($stmt)) {
throw new Exception(mysqli_stmt_error($stmt));
}
$code = null;
$name = null;
mysqli_stmt_bind_result($stmt, $code, $name);
while (mysqli_stmt_fetch($stmt)) {
$array[] = new Country($code, $name);
}
mysqli_stmt_close($stmt);
mysqli_close($link);
return $array;
}
$user_country = 'CHE';
?>
<select id="user_country" name="user_country">
<option value=""></option>
<?php
foreach (country_select_list() as $country) {
echo ' <option value="' . $country->code . '"';
if (isset($user_country) && $user_country == $country->code) {
echo ' selected="selected"';
}
echo ">" . $country->name . "</option>\r\n";
}
?>
</select>
This is the output
<select id="user_country" name="user_country">
<option value=""></option>
<option value="ITA">Italy</option>
<option value="CHE" selected="selected">Switzerland</option>
</select>
Related
I have problem, that if I not select any item from selection list, they not inserting element in my DB.
I put some come, that if I select value -1 from list, which is ------------, then they should make it NULL in that field.
There is my code.
<p>
<?php
if ($_POST['fk_KOMANDAid_KOMANDA'] == '-1') {
$_POST['fk_KOMANDAid_KOMANDA'] = NULL;}
?>
<label class="field" for="fk_KOMANDAid_KOMANDA">Komanda<?php echo in_array('fk_KOMANDAid_KOMANDA', $required) ? '<span> *</span>' : ''; ?></label>
<select id="fk_KOMANDAid_KOMANDA" name="fk_KOMANDAid_KOMANDA">
<option value="-1">---------------</option>
<?php
$kom = $asmuoObj->getkomanda();
foreach($kom as $key => $val) {
$selected = "";
if(isset($data['fk_KOMANDAid_KOMANDA']) && $data['fk_KOMANDAid_KOMANDA'] == $val['id']) {
$selected = " selected='selected'";}
echo "<option{$selected} value='{$val['id']}'>{$val['pavadinimas']}</option>";}
?>
</select>
</p>
This is INSERT function.
public function insertkomanda($data) {
$query = " INSERT INTO {$this->komanda_lentele}
(
`pavadinimas`,
`sutrumpinimas`,
`ikurimo_data`,
`svetaines_adresas`,
`fk_VALSTYBEid_VALSTYBE`,
`fk_RUNGTYNESid_RUNGTYNES`
)
VALUES
(
'{$data['pavadinimas']}',
'{$data['sutrumpinimas']}',
'{$data['ikurimo_data']}',
'{$data['svetaines_adresas']}',
'{$data['fk_VALSTYBEid_VALSTYBE']}',
'{$data['fk_RUNGTYNESid_RUNGTYNES']}'
)";
mysql::query($query);
}
When I press SUBMIT, then nothing happens, data not intserted in my DB. Should insert with fk_KOMANDAid_KOMANDA eaquls NULL.
I'd like to add "selected" attribute to a combo box. This is my PHP:
if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }
if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }
if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }
if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }
I may have over hundreds of IF's.
I've tried this one, but It seems not working:
for($a=1; $a<=4; $a++){
if($results['status'] == $a)
{ $ok = "selected"; }
else
{ $ok = ""; }
}
I'd like to make it as simple as possible. maybe 1 or 2 line. Because I have many combo box that should be treated this way
Edit (My combo box):
<select>
<option value="1" <?php echo $ok1; ?>>A</option>
<option value="2" <?php echo $ok2; ?>>B</option>
<option value="3" <?php echo $ok3; ?>>C</option>
<option value="4" <?php echo $ok4; ?>>D</option>
</select>
Since $results['status'] can only have 1 value, use dynamic variable names to make your life easy!
// initialize all 4 to blank
for($a=1; $a<=4; $a++){
${"ok" . $a} = "";
}
// set the one that is selected
${"ok" . $results['status']} = "selected";
This answer is very scalable, you can just change the number on the "for" line from 4 to 1000 and it works with no extra code added.
You can do this way,
<?php
// status list array
$selectValues = array(1, 2, 3, 4);
echo '<select name="combo_name">';
foreach($selectValues as $value){
$selected = "";
if($results['status'] == $value){
$selected = ' selected="selected" ';
}
echo '<option '.$selected.' value="'.$value.'">'.$value.'</option>';
}
echo '</select>';
?>
All you have to do is make an array and loop through it-
<?php
$results_status = 3; // What ever your retrieve variable value is. In your case: `$results['status']`
$arr = array("1" => "A",
"2" => "B",
"3" => "C",
"4" => "D"
);
?>
<select>
<?php
foreach($arr as $key => $val){
$sel = ($results_status == $key) ? "selected='selected'" : "";
?>
<option value="<?php echo $key?>" <?php echo $sel; ?>><?php echo $val?></option>
<?php }?>
</select>
You need to check every time for the selected value in the combo box.
Hope this helps
$combolength - the number of options in combo
$ok = array_fill(0, $combolength - 1, '');
switch ($results['status']) {
case $results['status']:
$ok[$results['status']]= 'selected';
break;
}
I personally think "simplify" what you already have is not the way to go about this. If you are not using a framework, I think you should instead ask how to make your script reusable, especially since you say "I have many combo box(es) that should be treated this way." Not using a contained element like a function/method sounds like a lot of extra work from a hardcoding standpoint. I personally would create a class that you can make form fields standardized and that you can feed an array into with dynamic key/value arrays. Simple example:
/core/classes/Form.php
class Form
{
# The idea here is that you would have many methods to build form fields
# You can edit this as you please
public function select($settings)
{
$class = (!empty($settings['class']))? ' class="'.$settings['class'].'"':'';
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':'';
$selected = (!empty($settings['selected']))? $settings['selected']:false;
$other = (!empty($settings['other']))? ' '.implode(' ',$settings['other']):'';
ob_start();
?>
<select name="<?php echo $settings['name']; ?>"<?php echo $other.$id.$class; ?>>
<?php foreach($settings['options'] as $key => $value) { ?>
<option value="<?php echo $key; ?>"<?php if($selected == $key) echo ' selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
To use:
# Include the class
require_once(__DIR__.'/core/classes/Form.php');
# You can use $form = new Form(); echo $form->select(...etc.
# but I am just doing this way for demonstration
echo (new Form())->select(array(
'name'=>'status',
'class'=>'classes here',
'id'=>'select1',
'other'=>array(
'data-instructions=\'{"stuff":["things"]}\'',
'onchange="this.style.borderColor=\'red\';this.style.fontSize=\'30px\'"'
),
# Options can be assign database returned arrays
'options'=>array(
'_'=>'Select',
1=>'A',
2=>'B',
3=>'C',
4=>'D'
),
'selected'=>((!empty($results['status']))? $results['status'] : '_')
));
Gives you:
<select name="status" data-instructions='{"stuff":["things"]}' onchange="this.style.borderColor='red';this.style.fontSize='30px'" id="select1" class="classes here">
<option value="_">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
I have some comboboxes with yes/no (value 1/0) that I store as a bit in my db. To put that value in the correct member of my object I do this:
class Member {
var $active;
public function refreshData() {
$mysqli = connectdbMySQLI();
$query = "SELECT * FROM tblMember WHERE ID = " . $this->id;
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
$this->setData($row);
$mysqli->close();
}
public function setData($row) {
$this->active = $row['active'];
}
}
Alle varchars, int and text-values or being assigned, except these bit values.
I checked with var_dump and I get an empty string
["active"]=> string(1) ""
Saving doesn't work as well:
$member = new Member(isset($_POST['id']) ? $_POST['id'] : null );
if(isset($_POST['active'])) {
$member->active = $_POST['active'];
$member->save();
}
This I use to select the right value in the combobox:
<select type="text" name="active" id="active" class="txt">
<option value="0" <?php echo $member->active == 0 ? 'selected="selected"' : ''; ?>>No</option>
<option value="1" <?php echo $member->active == 1 ? 'selected="selected"' : ''; ?>>Yes</option>
</select>**
What can be different than on my local NAS?
EDIT:
I tried this (all results are 1):
$this->active = $row['active'] == true ? '1' : '0';
and this (all results are 0):
$this->active = $row['active'] == 1? '1' : '0';
EDIT 2:
just tried a simple query (no mysqli) and I get an empty result for all my bit-fields
the following condition will only work if you have selected the value 1 from the active dropdown
if(isset($_POST['active']))
you need to replace it with the following
if(!$_POST['active']) {
$_POST['active'] = 0;
}else{
$_POST['active'] = 1;
}
OR Solution 2
update the following values in drop down
<select type="text" name="active" id="active" class="txt">
<option value="1" <?php echo $member->active == 1 ? 'selected="selected"' : ''; ?>>No</option>
<option value="2" <?php echo $member->active == 2 ? 'selected="selected"' : ''; ?>>Yes</option>
</select>**
it will not bypass your if condition.
I am looking for some method to select a php combobox "<select>" based on results from mysql.
Actually I am working on a php form that will be used to edit existing values in mysql table. My first form will simply pass the id of the record to be edited, and this goes something like this Click to edit
Code on editCalendar.php is as follows:
<?php
include("dbpath.php");
$id = htmlspecialchars($_GET["id"]);
$sql="Select * from event_Date where eventid=" . $id;
$result=mysql_query($sql);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result)
{
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row = mysql_fetch_assoc($result))
{
$name=$row["EventTitle"];
$close=$row["OpenOrClose"];
$remarks=$row["Remarks"];
$date=$row["EventDate"];
$type=$row["Type"];
}
?>
The value obtained in $close will be used to select "SelectClosedOrOpen" on the same form, i.e. the user will get pre selected option from the populated list.
<select id="SelectClosedOrOpen">
<option value="3">Select</option>
<option value="0">Open</option>
<option value="1">Closed</option>
</select>
Means, if $close has 0, then <option value="0">Open</option> must be selected else if $close has 1 then <option value="1">Closed</option> should be automatically selected on formload.
You'll just need to write the selected attribute in there. Try this
<select id="SelectClosedOrOpen">
<option value="3" <?php echo ($close == 3) ? 'selected="selected"': ''; ?>>Select</option>
<option value="0" <?php echo ($close == 0) ? 'selected="selected"': ''; ?>>Open</option>
<option value="1" <?php echo ($close == 1) ? 'selected="selected"': ''; ?>>Closed</option>
</select>
I created this function some years back. I hope it helps you.
It basically requires an array of your options and the value of the option to be pre-selected. It returns the OPTIONS for your select, so you still have to create the SELECT tags, which allows you to customise the ID, JS etc..
function drop_down_box_options_from_array($choices,$default="")
{
$output= '';
// $choices is contructed using $choices[]=array("value","Displayed Choice");
while (list ($key, $val) = each ($choices))
{
$output.= '<option value="';
$output.= $choices[$key][0];
if ($default==$choices[$key][0])
{
$output.= '" selected="selected" >';
}
else
{
$output.= '">';
}
$output.= $choices[$key][1];
$output.= '</option>';
$output.= "\n";
}
return $output;
}
Using your scenario:
<select id="SelectClosedOrOpen" name="OpenOrClose">
<?php
// defined here for clarity, but can be defined earlier ie in a config file
$choices[]=array('3', 'Select');
$choices[]=array('0', 'Open');
$choices[]=array('1', 'Closed');
echo drop_down_box_options_from_array($choices, $row['OpenOrClose']);
?>
</select>
I've a table with multiple rows, each row has a drop down list. I am new to javascript and is unable to retrieve the selected value from the row. Any idea how can it be done? Thanks in advance.
Code:
function chng_page(serialNum, rowid)
{
alert(rowid);
alert(serialNum);
var select_index = document.getElementById('orderStatus').selectedIndex;
//get the value of selected option
var option_value = document.getElementById('orderStatus').options[select_index].value;
//redirect with value as a url parameter
window.location = 'orderStatus.php?serialNum=' + serialNum + '&status=' + option_value;
}
</script>
//code for drop down list
<select id="orderStatus" name="orderStatus" onchange="chng_page(<?php echo $serialNum? >, this.parentNode.parentNode.rowIndex)">
<option value="Pending" <?php echo ($status == "Pending") ? ' selected="selected"' : ''; ?>>Pending</option>
<option value="Cooking" <?php echo ($status == "Cooking") ? ' selected="selected"' : ''; ?>>Cooking</option>
<option value="On The Way" <?php echo ($status == "On The Way") ? ' selected="selected"' : ''; ?>>On The Way</option>
<option value="Delivered" <?php echo ($status == "Delivered") ? ' selected="selected"' : ''; ?>>Delivered</option>
</select>
You didn't mention if the select element in each row has a unique id or not, but it somehow shows in your code that they do.
In that case, you can use JQuery (a popular JavaScript framework) to retrieve the selected value.
Assuming you have included the JQuery file in your HTML, and attached an event handler to the select element (to make it easier, pass in the id of the current select element as a parameter in the function), do this:
var selected_value = $("#id_of_select_element option:selected").val();
If the ids of the select elements are unique, that single line of code will definitely work.
You have the same name/id for the drop down in all table rows
If there is a dropdownlist in each row with same id-> #orderStatus, you should try this,
function chng_page(serialNum, ddlist)
{
var rowid = ddlist.parentNode.parentNode.rowIndex
alert(rowid);
alert(serialNum);
var select_index = ddlist.selectedIndex;
//get the value of selected option
var option_value = ddlist.options[select_index].value;
//redirect with value as a url parameter
window.location = 'orderStatus.php?serialNum=' + serialNum + '&status=' + option_value;
}
<select name="orderStatus" onchange="chng_page(<?php echo $serialNum?>, this)">
<option value="Pending" <?php echo ($status == "Pending") ? ' selected="selected"' : ''; ?>>Pending</option>
<option value="Cooking" <?php echo ($status == "Cooking") ? ' selected="selected"' : ''; ?>>Cooking</option>
<option value="On The Way" <?php echo ($status == "On The Way") ? ' selected="selected"' : ''; ?>>On The Way</option>
<option value="Delivered" <?php echo ($status == "Delivered") ? ' selected="selected"' : ''; ?>>Delivered</option>
</select>