How To Dropdown Select using PHP/MYSQL - php

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 . '|--');
}
}
};

Related

Reduce size of function

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;
}

Yii2 recursion of the tree menu?

Good night all! Help please in the recursion, where I made a mistake, I need to output the categories, as in the last example!
Model:
protected function buildTree($data, $rootID = 0)
{
$tree = [];
foreach ($data as $id => $node) {
if ($node->parent_id == $rootID) {
unset($data[$id]);
$node->childs = $this->buildTree($data, $node->id);
$tree[] = $node;
}
}
return $tree;
}
public function getTree()
{
$data = Category::find()->all();
return $this->buildTree($data);
}
View:
<?php $form = ActiveForm::begin()
foreach ($tree as $cat) {
echo '<br><div class="spoiler-title">' . $cat['title'] . '</div>';
printNode($cat);
}
function printNode($cat, $level = 1)
{
if (count($cat['childs']) > 0) {
foreach ($cat['childs'] as $child) {
for ($j = 1; $j < $level; $j++) {
echo '------- <b>';
}
echo '' . $child['title'] . '</b><br>';
//echo $form->field($model, $child['title'])->checkbox();
//I want to do a checkbox, get an error, do not understand $
//form and $ model
if (count($child['childs']) > 0) {
printNode($child, $level + 1);
}
}
}
}
$form = ActiveForm::end() ?>
That's how I get the tree, this is with your code
root
category
category
category
---- <b>subcategory</b
---- <b>subcategory</b
---- <b>subcategory</b
---- <b>subcategory</b
category
category
I need to make checkboxes in subcategories, but I get an error, in the code I wrote in the comments, your code works, but I can not change it my needs as a picture.
You should also add recursion in view when you print tree.
Try this in view:
$form = \yii\bootstrap\ActiveForm::begin();
foreach ($tree as $cat) {
printNode($cat);
}
function printNode($cat, $level = 1) {
echo '<br><div class="spoiler-title">' . $cat['title'] . '</div>';
if (count($cat['childs']) > 0) {
foreach ($cat['childs'] as $child) {
echo \yii\helpers\Html::checkbox('someName[]') . ' ' . $child['title'] . '<br>';
if (count($child['childs']) > 0) {
printNode($child, $level + 1);
}
}
}
}
\yii\bootstrap\ActiveForm::end();

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>';
}

Return all row in while loop for Dropdown select box option

I am trying to return all row as a select box Option but it is returning only first row
while($parent_cat = mysql_fetch_array( $result ))
{
return '<option value="'.$parent_cat['categoryid'].'">'.$parent_cat['title'].'</option>';
}
How can I return all row?
You can expand on below function by passing some attributes as parameters and building the dynamic drop down as you wish.
function showDropDown() {
$html = '<select>';
$i = 0;
while (your loop condition) {
$html .= '<option value="">Hello World</option>';
$i++;
}
$html .= '</select>';
//in case your loop fails return empty instead of drop down without options.
return $i > 0 ? $html : '';
}
echo showDropDown();
The way i use above function is:
function buildDropDown(array $array, $attributes = array()) {
if (! empty($array)) {
$html = '<select ';
foreach($attributes as $attr => $val) {
$html .= $attr . '="' . $val . '" ';
}
foreach($array as $key => $value) {
$html .= '<option value="'.$key.'">'.$value.'</option>';
}
$html .= '</select>';
return $html;
}
return '';
}
$testArr = array(1 => 'A', 2 => 'B', 3 => 'C');
$attrs = array(
'id' => 'hello',
'name' => 'hello',
'style' => 'background-color: blue'
)
echo buildDropDown($testArr, $attrs);
above generates:
<select id="hello" name="hello" style="background-color:blue">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
I managed to pull this off this way.
function openDB()
{
global $conn, $username,$host,$password,$db;
$host = "localhost";
$username ="username";
$password= "password";
$db = "databasename";
$conn = mysql_connect($host, $username,$password) or die(mysql_error());
mysql_select_db($db,$conn) or die(mysql_error());
}
function closeDB()
{
global $conn;
mysql_close($conn);
}
openDB();
$query3 = "select * from table_name";
$result2 = mysql_query($query3,$conn)
or die ("Error in query: $query.". mysql_error());
// if a result
if(mysql_num_rows($result) > 0)
{
//turn it into an object
$row = mysql_fetch_object($result);
if(mysql_num_rows($result2) > 0)
{
//turn it into an object
$row2 = mysql_fetch_object($result2);
?>
<?
//creates a options box for the list of items in the dropdownmenu
echo"<select>";
while($row2=mysql_fetch_array($result2))
{
echo "<option>".$row2['feild_title']."</option>";
}
echo"</select>";
closeDB();
?>

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