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;
Related
Yo!
I have this code. Basically it should return a list of avaiable jobs based on the location and what position user looked for...
I am trying to figure out how to shorten the execution time for this...
$cities = $this->getChildren($location->city_id);
foreach ($cities as $child) {
$grandChildren = $this->getGrandChildren($child, false);
foreach ($grandChildren as $grandChild) {
$cities[] = $grandChild;
}
}
$menu = $this->getPositionChildren($postion);
$menu[] = $postion->menu_id;
// var_dump($cities);
foreach ($cities as $city) {
$city_id = (!empty($city) ? "AND FIND_IN_SET('{$city}', town)" : '');
foreach ($menu as $key) {
$menu_id = (!empty($key) ? " AND FIND_IN_SET('{$key}', category_id)" : '');
$queries[] = "SELECT ponuka_id as id FROM " . TABLE_PREFIX . "ponuky WHERE 1 {$city_id} {$menu_id} AND `published` = '1' ORDER BY `date` DESC";
foreach ($queries as $query) {
$result = mysql_query($query);
if (!$result) {
return false;
}
while ($row = mysql_fetch_object($result)) {
if (!in_array($row->id, $this->_joblist, true)) {
$this->_joblist[] = $row->id;
}
}
}
}
The code above can easily run over 1000 queries and as you can imagine, this takes time... Long time... any tips on how to improve this?
The code now looks like this and by taking the query out of the loop it runs a lot faster...
$cities = $this->getChildren($location->city_id);
foreach ($cities as $child) {
$grandChildren = $this->getGrandChildren($child, false);
foreach ($grandChildren as $grandChild) {
$cities[] = $grandChild;
}
}
// $cities = $this->getCityInfoFromArray($cities);
$menu = $this->getPositionChildren($postion);
$menu[] = $postion->menu_id;
var_dump($cities);
foreach ($cities as $city) {
$city_id = (!empty($city) ? "AND FIND_IN_SET('{$city}', town)" : '');
foreach ($menu as $key) {
$menu_id = (!empty($key) ? " AND FIND_IN_SET('{$key}', category_id)" : '');
$queries[] = "SELECT ponuka_id as id FROM " . TABLE_PREFIX . "ponuky WHERE 1 {$city_id} {$menu_id} AND `published` = '1' ORDER BY `date` DESC";
}
}
foreach ($queries as $query) {
$result = mysql_query($query);
if (!$result) {
return false;
}
while ($row = mysql_fetch_object($result)) {
if (!in_array($row->id, $this->_joblist, true)) {
$this->_joblist[] = $row->id;
}
}
}
You can try it like this. Check if this works for you.
$city_id = ""; $city_id = "";
foreach ($cities as $city) {
$city_id .= (!empty($city) ? " AND FIND_IN_SET('{$city}', town)" : '');
foreach ($menu as $key) {
$menu_id .= (!empty($key) ? " AND FIND_IN_SET('{$key}', category_id)" : '');
}
}
$result = mysql_query("SELECT ponuka_id as id FROM " . TABLE_PREFIX . "ponuky WHERE 1 {$city_id} {$menu_id} AND `published` = '1' ORDER BY `date` DESC");
in my for each loop I want to sort my options by the value of my variable $total resp. by the data-total:
<select>
<option data-total="0" value="" selected>--</option>
<?php
$pdo = Database::connect();
$sql = "SELECT * FROM table_a;" ;
foreach ($pdo->query($sql) as $row) {
$a = $row['a'];
$number_a = $row['number_a'];
$sql2 = "SELECT * FROM table_b WHERE a = '$a';" ;
$number_b = 0;
foreach ($pdo->query($sql2) as $row2) {
$number_b+= $row2['number'];
}
$total = $number_a - $number_b;
echo '<option data-total="'.$total.'" value="'.$a.'">'.$a;
}
Database::disconnect();
?>
</select>
Is this possible? Thank you very much!
In your for loop do something like this
$total_arr = array();
foreach ($pdo->query($sql) as $row) {
$a = $row['a'];
$number_a = $row['number_a'];
$sql2 = "SELECT * FROM table_b WHERE a = '$a';" ;
$number_b = 0;
foreach ($pdo->query($sql2) as $row2) {
$number_b+= $row2['number'];
}
$total = $number_a - $number_b;
$total_arr[$a] = $total;
}
arsort($total_arr);
foreach ($total_arr as $key => $val) {
echo '<option data-total="'.$val.'" value="'.$key.'">'.$key;
}
i have small page with cart. All things is storage in session. Now i need to save this data to mysql databse.
I think, that i need use foreach cycle to do this, but i cant construct it. Does anybody know the solution?
This is the function that displays cart.
function showCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$total=0;
$output[] = '<table>';
foreach ($contents as $id_menu=>$qty) {
$sql = 'SELECT * FROM menu WHERE id_menu = '.$id_menu;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>Delete</td>';
$output[] = '<td>' .$name. '</td>';
$output[] = '<td>' .$price.' Kč</td>';
$output[] = '<td><input type="text" name="qty'.$id_menu.'" value="'.$qty.'" size="5" maxlength="5" /></td>';
$output[] = '<td>' .($price * $qty).' Kč</td>';
$total += $price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Total: <strong>'.$total.' EUR</strong></p>';
$output[] = '<div><button type="submit">Update</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>Cart is empty.</p>';
}
return join('',$output);
}
i think you need something like this....
foreach ($contents as $id_menu=>$qty)
{
$sql1 = 'INSERT INTO tablename (colum1, colum2, column3, ... ) SELECT * FROM menu WHERE id_menu = '.$id_menu;
//rest of your program
}
You can use:
Insert into mytable SELECT * FROM menu WHERE id_menu = ...
To construct the multiple insert and insert all in one statement, do the following:
Insert into mytable (col1, col2, col3) values
('Val1a','val2a','val3a'),
('Val1b','val2b','val3b'),
('Val1f','val2d','val3c'),
Etc...
;
Each iteration will concatenate one line of values. Insert is then done after the loop.
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 . '|--');
}
}
};
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();
?>