Reduce size of function - php

I've created this function below but i'm sure i'm doing it inefficiently ( less code ).
Is there a better way to do it?
function Select_Workorder_Type($Selected = NULL){
$q = DB::query("SELECT * FROM `tbl_workorders_type`");
$v = '<select id="Workorder_Type" name="Workorder_Type" class="Formfield_Select" required>';
foreach ($q as $r) {
if ($r['Workorders_Type_ID'] == $Selected) {
$s = 'selected="selected"';
}
$v .= '<option '.$s.' value="'.$r['Workorders_Type_ID'].'" >' . $r['Workorders_Type_Name'] . '</option>';
unset($s);
}
$v .= '</select>';
echo $v;
}

Related

Check if any comma seperated value exists inside loop values

I get some values from an old db of a client as such:
$query = "SELECT rowid,source FROM `".$table."`";
$result = mysql_query($query);$temp=0;$p = array();
while ($row = mysql_fetch_array($result)) {$p[$temp] = $row;$temp++;}
and then I loop through the values as such:
// loop through all possible values
foreach ($p as $obj) {
}
Inside the foreach loop I will print <option> element and I want to determine the <option selected/> elements. The selected elements could be more than 1, since its a multiselect form.
First thing I check whether a $selected value equals to rowid.
// check if exists equals to rowid
if ($obj["rowid"] == $selected){
$return .= '<option value="'.$obj["rowid"].'" selected>'.$obj["source"].'</option>';
}else{
$return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
This works just find if $selected = "1" (or any single digit)
My problem and my question comes if $selected = "3,4". Then I need to loop through the values and separate the comma-separated values inside foreach ?
Here is my complete code:
$selected = "3,4";
$query = "SELECT rowid,source FROM `" . $table . "`";
$result = mysql_query($query);
$temp = 0;
$p = array();
while ($row = mysql_fetch_array($result)) {
$p[$temp] = $row;
$temp++;
}
// loop through all possible values
foreach($p as $obj) {
// check if exists equals to rowid
if ($obj["rowid"] == $selected) {
$return.= '<option value="' . $obj["rowid"] . '" selected>' . $obj["source"] . '</option>';
}
else {
// check if default exists with comma separated values
if (!empty($default) && strpos($selected, ',') !== false) {
$arr_values = explode(',', $selected);
// loop through comma-separated values to get the selected items
foreach($arr_values as $selected) {
if ($obj["rowid"] == $default) {
$return.= '<option value="' . $obj["rowid"] . '" selected>' . $obj["source"] . '</option>';
}
}
// $return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
else {
$return.= '<option value="' . $obj["rowid"] . '">' . $obj["source"] . '</option>';
}
}
}
Just use in_array() + explode() functions combination to check if rowid exists in selected string
if (in_array ($obj["rowid"], explode(",",$selected))){
$return .= '<option value="'.$obj["rowid"].'" selected>'.$obj["source"].'</option>';
}else{
$return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
Explanation: E.G. if $selected = "3,4" then explode(",",$selected) return you array(3,4) and in_array check if $obj["rowid"]' exists in that array so it mean you will have in you output multiple <options with attribute selected set

PHP check array into array or multidimensional array

i want to create HTML element with PHP functions. in this section i have select function to create select tag. for values i want to check if array is simple my function create simple select otherwise create optgroup for options.
my create select method :
$tag->select( 'myselect',
array(
'0'=>'please choose','1'=>'111','2'=>'222','3'=>'333'
) ,
'2',
array(
'class'=>'myClass','style'=>'width:10%;'
)
);
other use:
$tag->select( 'myselect',
array( 'one'=>
array('0'=>'please choose','1'=>'111','2'=>'222','3'=>'333'),
'two'=>
array('0'=>'please choose','1'=>'111','2'=>'222','3'=>'333')
) ,
'2',
array(
'class'=>'myClass','style'=>'width:10%;'
)
) ;
now in below function i want to check if array into array exist function must be create select group;
public function select( $name, $values, $default='0', $attributs=[]){
$options = [];
$selected = '';
echo count($values);
if ( count($values) == 1){
foreach ($values as $value => $title) {
if ( $value === $default ) $selected="selected='selected'";
$options[] = "<option value = '$value' $selected>" . $title . '</option>'.PHP_EOL ;
$selected = '';
}
}
else{
foreach ($values as $key => $value) {
$options[] = "<optgroup label='$key'>";
foreach ($value as $selectValue => $title) {
$options[] = "<option value = '$selectValue'>" . $title . '</option>'.PHP_EOL ;
}
$options[] = "</optgroup>";
}
}
$selectTag = '<select ' . $this->setAttribute($attributs) . '>'.PHP_EOL;
return $selectTag . implode($options, ' ') . '</select>';
}
this function is not correct. how to resolve that? thanks.
Try this (hopefully helps you)
public function select( $name, $values, $default='0', $attributs=[]){
$options = [];
$selected = '';
echo count($values);
foreach ($values as $key => $value) {
if (!is_array($value)) {
if ( $key === $default ) $selected="selected='selected'";
$options[] = "<option value = '$key' $selected>" . $value . '</option>'.PHP_EOL ;
$selected = '';
}
else {
$options[] = "<optgroup label='$key'>";
foreach ($value as $selectValue => $title) {
$options[] = "<option value = '$selectValue'>" . $title . '</option>'.PHP_EOL ;
}
$options[] = "</optgroup>";
}
}
$selectTag = '<select ' . $this->setAttribute($attributs) . '>'.PHP_EOL;
return $selectTag . implode($options, ' ') . '</select>';
}

How To Dropdown Select using PHP/MYSQL

i have this function for print categories in dropdown menu.
function Cat_Parent(){
$result = mysql_query("SELECT id, name, parent FROM cats ORDER BY name");
$items = array();
while($row = mysql_fetch_array($result))
{ $items[] = array('id' => $row['id'], 'label' => $row['name'], 'parent' => $row['parent']);
}
// Loop using references to build a tree
$childs = array();
foreach($items as &$item)
{
$childs[$item['parent']][] = &$item;
}
unset($item);
foreach($items as &$item)
{
if(isset($childs[$item['id']]))
{
$item['children'] = $childs[$item['id']];
}
}
// We now have a tree with 'children' key set on each node that has children
$tree = $childs[0];
// Prepare a template and recursive closure (note reference on &$print)
$tpl = '<option name="parent[]" value="%s">%s %s</option>';
$print = function($item, $indent = '') use (&$print, $tpl)
{
echo sprintf($tpl, $item['id'], $indent, $item['label']) . "\n";
if(isset($item['children']))
{
foreach($item['children'] as $child)
{
$print($child, $indent . '|--');
}
}
};
echo '<select name="parent"><option name="parent[]" value="0">------</option>';
// Call the function for each top-level node
foreach($tree as $row)
{
$print($row);
}
echo '</select>';
}
this worked but i need to selected value/id when$_GET['id'] = value Like This:
<select>
<option value="1">cat1</option>
<option selected value="2">cat2</option> <-- THIS Print Selected
<option value="3">subcat2</option>
<option value="4">cat3</option>
<option value="5">cat4</option>
</select>
in example $_GET['id'] = 2 , so selected option with value 2. how to select this?
Try this code in your script. Defines a variable with "selected" value if the value from GET is the same as the option value.
Notice the $sel variable.
// Prepare a template and recursive closure (note reference on &$print)
$tpl = '<option name="parent[]"%s value="%s">%s %s</option>';
$print = function($item, $indent = '') use (&$print, $tpl)
{
$sel = (isset($_GET['id']) && $_GET['id'] == $item['id']) ? 'selected' : ' ';
echo sprintf($tpl, $sel, $item['id'], $indent, $item['label']) . "\n";
if(isset($item['children']))
{
foreach($item['children'] as $child)
{
$print($child, $indent . '|--');
}
}
};
You're going to want to compare your values in the template like so:
$tpl = '<option name="parent[]" %s value="%s">%s %s</option>';
$print = function($item, $indent = '') use (&$print, $tpl)
{
echo sprintf($tpl, $item['id'] == 2 ? 'selected="selected"' : '', $item['id'], $indent, $item['label']) . "\n";
if(isset($item['children']))
{
foreach($item['children'] as $child)
{
$print($child, $indent . '|--');
}
}
};

Undefined Offset 0 , how can i set this array

Hello i have an Undefined Offset 0 . inside this code.
$q = mysql_query("SELECT * FROM category");
if (false === $q) {
echo mysql_error();
}
while ($r = mysql_fetch_row($q)) {
$names[$r[0]] = $r[2];
$children[$r[0]][] = $r[1];
}
function render_select($root=0, $level=-1) {
global $names, $children;
if ($root != 0)
echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
foreach ($children[$root] as $child)
render_select($child, $level+1);
}
echo '<select>';
render_select();
echo '</select>';
The exact line where the error is :
foreach ($children[$root] as $child)
render_select($child, $level+1);
This is for a selectbox with a tree format, i found this code in this question
More efficient hierarchy system
There is some ambiguity in your code here:
if ($root != 0)
echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
foreach ($children[$root] as $child)
render_select($child, $level+1);
If you are attempting to execute these three lines only if $root != 0, you will need to add curly braces like this:
if ($root != 0)
{
echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
foreach ($children[$root] as $child)
{
render_select($child, $level+1);
}
}
Otherwise, anytime render_select is called without a parameter (or with a first parameter value of '0') you will attempt to access the element of $children at array key '0'. As your error indicates, $children does not contain a value at that key.

Multi level selectbox

I have a problem with building multi level select box. I have category table with structure: id, parent_id, name. If parent_id = 0 it is top level. i don't know level depth, so it could be 2,3-5 levels.
How i can build it with on query "SELECT * FROM cats"
Result suppose to look like
<select>
<option>cat_name</option>
<option>--cat_name_l1</option>
<option>--cat_name_l1</option>
<option>----cat_name_l2</option>
<option>----cat_name_l2</option>
<option>cat_name</option>
</select>
Can You help me?
function _buildTree($data, $idParent, $indentSymbol, $level)
{
$cat = array();
foreach($data as $row){
if($row['parent_id'] == $idParent){
if($indentSymbol AND $level > 0){
$symbols = array_fill(0, $level, $indentSymbol);
$cat[$row['id']] = implode('', $symbols) . $row['name'];
}else{
$cat[$row['id']] = $row['name'];
}
$cat = $cat + _buildTree($data, $row['id'], $indentSymbol, $level++);
}
}
return $cat;
}
$result = mysql_query("SELECT * FROM cats");
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
$select = '<select>';
foreach(_buildTree($data, 0, '-', 0) as $key=>$option){
$select .= '<option value=' . $key . '>' . $option . '</option>';
}
$select .= '</select>';
Try this for generating the required dropdown:
$result=mysql_query("SELECT * FROM cats");
$opt='<select>';
while($row=mysql_fetch_array($result))
{
$cat[$row['id']][0]=$row['parent_id'];
$cat[$row['id']][1]=$row['name'];
}
foreach($cat as $ct)
{
$level=0;
$temp=$ct;
while($temp[0]!=0)
{
$temp=$cat[$temp[0]];
$level++;
}
$opt.="<option>";
for($i=0;$i<$level;$i++)
{
$opt.="--";
}
$opt.=$ct[1];
$opt.="</option>";
}
$opt.="</select>";
Then, you can use this as:
echo $opt;

Categories