recursive function using php for getting level in binary tree - php

I want to get level in the binary tree. I am getting already tree and insertion point but there is a problem in getting pair matching and level. The binary tree image is attached
here
how to stop recursive function after level 3.
my code is given below
function getTree($parent_id, $level){
global $conn;
$sql2 = "SELECT * FROM user WHERE parent_id='".$parent_id."' ORDER BY `rightorleft`";
$result2 = $conn->query($sql2);
$i=0;
static $calls=0;
if (mysqli_num_rows($result2) > 0)
{
echo "<ul>";
while ($row2 = mysqli_fetch_object($result2))
{
echo '<li>';
echo '<div><img src="images/user.png" width="40" height="40"><br>'.$row2->user_id.'</div>';
getTree($row2->id,$level++);
echo '</li>';
}
echo "</ul>";
}
}
I want to result only for 2 level like this

Try using $level as a counter to stop the recursion calls.
By calling the function with $level = 3 should give you the desired result.
function getTree($parent_id, $level)
{
global $conn;
// Stop when $level is 0 or less
if($level <= 0) return ;
$sql2 = "SELECT * FROM user WHERE parent_id='".$parent_id."' ORDER BY `rightorleft`";
$result2 = $conn->query($sql2);
$i = 0;
static $calls = 0;
if (mysqli_num_rows($result2) > 0)
{
echo "<ul>";
while ($row2 = mysqli_fetch_object($result2))
{
echo '<li>';
echo '<div><a href="#"><img src="images/user.png" width="40"
height = "40" >< br > '.$row2->user_id.' </ a ></ div > ';
// Recursively go deeper, use $level-1 here
getTree($row2->id,$level-1);
echo '</li>';
}
echo "</ul>";
}
}

Related

Limiting bootstrap pagination in PHP to 5 pages

I'm trying to create pagination in PHP where 5 pages are displayed.
When on the first page we have:
[1][2][3][4][5] ...[325][>>]
Clicking on [325] will take you to that page (the last record), clicking on the right arrow will take you to page [2].
When on the second page we have:
[<<][1]...[2][3][4][5][6] ...[325][>>]
And when on the last page we have:
[<<][1]...[321][322][323][324][325]
I've been researching on how to do this without much luck. I think I understand that I need to create an array with adjacent pages of 2 on each side of the active page, when we are on any page except the first or last page. I also need to create an <li>1</li>
and
<li><?php echo $last_record; ?></li>
for when a user is anywhere but the first or last record.
I have the following code which works great, however when we start getting a large number of records, the pagination count gets ridiculous.
<ul class="pagination pull-left pagination-md">
<?php
// Creates back button in pagination
if(isset($page)) {
if($page > 1) {
$page_minus = $page-1;
echo "<li><a href='blog.php?page=$page_minus'> « </a></li>";
}
}
?>
<?php
global $con;
$q_pagination = mysqli_prepare($con, "SELECT COUNT(*) FROM admin_panel WHERE ");
$q_pagination->execute();
$result_pagination = $q_pagination->get_result();
$rows_result = $result_pagination->fetch_array();
$total_rows = array_shift($rows_result);
$post_per_page = $total_rows/15;
$post_per_page = ceil($post_per_page);
for($i = 1; $i <= $post_per_page; $i++) {
if(isset($page)){
if($i == $page) {
echo "<li class='active'><a href='blog.php?page=$i'>$i</a></li>";
}
else {
echo "<li><a href='blog.php?page=$i'>$i</a></li>";
}
}
}
// Creates the forward button in pagination
if(isset($page)){
if($page+1 <= $post_per_page) {
$page_plus = $page+1;
echo "<li><a href='blog.php?page=$page_plus'> » </a></li>";
}
}
?>
</ul>
I'll admit, after researching and attempting to make this work I'm just getting twisted in the logic. Does anyone have any thoughts on how to best approach this? Leads, current examples, etc. Most of what I've found is dated, incomplete, or stupid long.
<?php
session_start();
include "mysqli_connect.php";
$companyID = $_SESSION['compid'];
$db = new Database();
$dbc = $db->getConnection();
$display = 3; //number of records per page
$pages;
$dbb = new Database();
$dbcb = $dbb->getConnection();
$stat = "select * from reservationStatus where resStatId = '$companyID' ";
$r = mysqli_query($dbcb, $stat);
//variable for sorting - default is for registration date
$sort = (isset($_GET['sort'])) ? $_GET['sort'] : 'rd';
switch ($sort)
{
case 'ln':
$orderby = 'uniquenumber ASC';
break;
case 'fn':
$orderby = 'status ASC';
break;
case 'rd':
$orderby = 'resId ASC';
break;
case 'em' :
$orderby = 'resDate ASC';
break;
default:
$orderby = 'resId ASC';
break;
}
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//get the total number of records from the table
$q = "select count(resId) from reservation where companyID = '$companyID'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //$display is the number of records per page
//ceil rounds fractions up to integer value
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//$q = "select * from users LIMIT $start, $display";
$q = "select * from reservation where companyID = '$companyID' order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
if($r)
{
echo '<br />';
//display a table of results
echo '<div class="container">';
echo '<h1> Your Orders </h1>';
echo '<table align="center" class="table table-bordered table-striped" width="60%">';
echo '<tr bgcolor="#87CEEB">
<td><b>View</b></td>
<td><b>Change Status</b></td>
<td><b> Reference Number</b></td>
<td><b>Status</b></td>
<td><b>Date</b></td>
<td><b>Total Price</b></td></tr>';
//above is the header
//loop below adds the user details
//use the following to set alternate backgrounds
$bg = '#eeeeee';
while($row = mysqli_fetch_array($r))
{
$stat = "select * from reservationStatus where resStatusId = $row[7] ";
$rr = mysqli_query($dbcb, $stat);
$roww = mysqli_fetch_array($rr);
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee');
echo '<tr bgcolor="' . $bg. '">
<td>View</td>
<td>Change Status </td>
<td>'.$row[2].'</td>
<td>'.$roww[1].'</td>
<td>'.$row[1]. ' ' . $row[8].'</td>
<td>'.$row[3].'</td>
</tr>';
}
echo '</table></div>';
}
else
{
echo '<p class="error">' . $q . '</p>';
echo '<p class="error"> Oh dear. There was an error</p>';
echo '<p class="error">' . mysqli_error($dbc) .'</p>';
}
mysqli_free_result($r);
//makes links to other pages if required
if($pages > 1)
{
echo '<br /><p> ' ;
//find out what page we are on
$currentpage = ($start/$display)+1;
//need a previous button if not first page
if($currentpage != 1)
{
echo ' <a href="viewOrdersForCompanies.php?$s=' . ($start - $display) .
'&p=' .$pages . '&sort='.$sort.'">&nbspPrevious&nbsp</a>';
}
//create the numbered pages
for($i = 1; $i <= $pages; $i++)
{
if($i != $currentpage)
{
//the 's' paramater is used in the link to determine which the value
// in the LIMIT clause used in the select statement near the top of the page
echo '<a href="viewOrdersForCompanies.php?s=' . (($display * ($i-1))) . '&p='
. $pages . '&sort='.$sort.'">&nbsp' . $i . '&nbsp</a>';
}
//&nbsp is a character to insert a whitespace
}
//if not last page create next button
if($currentpage != $pages)
{
echo '<a href="viewOrdersForCompanies.php?s=' . ($start+$display) . '&p=' . $pages
. '&sort='.$sort.'">&nbspNext&nbsp</a>';
}
echo '</p>';
}
?>

Warp two row with a class after query

I want to warp every two row with a class. So I saw some guideline from here and googling and found foreach array_chunk to do this. And I tried as below which can't display any result. Without foreach its work well. Were is my wrong here please?
In the above picture that I want to do; my every two category warp with a class. And add a divider after each top category.
Here is my tried:
echo '<ul class="dropdown-menu dropdown-menu-large row">';
$sql = "SELECT id,name FROM main_cata ORDER BY id ASC";
$execute = $dbh->query("$sql");
$rowcount = $execute->num_rows ;
$row = $dbh->query($sql) ;
while ($row = $execute->fetch_assoc()) {
foreach (array_chunk($row, 2, true) as $array){
echo'<li class="col-sm-3">';
foreach($array as $rows){
echo '<ul><li class="dropdown-header">'.$rows->name.'</li>';
$sql2 = "SELECT id,name,page FROM catagory WHERE m_cata = '".$rows->id."' ORDER BY id ASC";
$execute2 = $dbh->query("$sql2");
$rowcount2 = $execute2->num_rows ;
$row = $dbh->query($sql) ;
while ($row = $execute2->fetch_assoc()) {
$cid = $row['id'];
$cname = $row['name'];
$page = $row['page'];
echo '<li>'.$cname.'</li>';
}
echo '<li class="divider"></li></ul>';
}
echo '</li>';
}
}
echo '</ul>';
while ($row = $execute->fetch_assoc()) {
fetch_assoc returns 1 row (id, name) from the query, then you are using the result and spliting in 2 (https://secure.php.net/manual/pt_BR/mysqli-result.fetch-assoc.php), What you can do is, make a counter instead of the array chunk that resets every time it reachs 2.
foreach (array_chunk($row, 2, true) as $array){
The content of $row is, for example, array('id' => 1, 'name' => 'Category 1').
foreach($array as $rows){
You are iterating again without needing to.
A simple version:
counter = 0;
echo "<ul>";
while (row = execute->fetch_assoc()) {
if (counter == 0) {
echo "init li";
}
echo "subinit li";
get subcategories
while (row2 = execute2->fetch_assoc()) {
print content
}
echo "subend li";
if (counter == 2) {
counter == 0;
echo "end li";
} else {
counter++;
echo "divider";
}
}
echo "</ul>";

It won't loop in a foreach or while

I'm trying to make this take 6 times, and then roll over into another row. I'm sure there's a better way of going about this, and that's probably why mine doesn't work.
However, when I use the foreach() it displays nothing, and when I use the while() the page breaks completely. The headers don't send, and php_error doesn't catch it.
All the queries work just fine, it's the display that's causing issues.
Perhaps you guys can help?
public static function DisplayInv($user) {
$user = users::lookup($user);
$sql = mysql_query("SELECT * from `inventory` where `userid`='{$user['id']}'");
$limit = 6;
$count = 0;
$fetch = mysql_fetch_array($sql) or die('Error: '.mysql_error());
while($count <= 7) {
print "<div class='row-fluid show-grid'>";
foreach($fetch as $items) {
$getItem = self::ItemInfo($items['itemid']);
print "<span class='span2'><b>{$getItem['name']}</b><br />{$getItem['description']}<br /><b>Power: {$getItem['power']}</b></span>";
$count++;
}
/* while($items = mysql_fetch_array($sql)) {
$getItem = self::ItemInfo($items['itemid']);
print "<span class='span2'><b>{$getItem['name']}</b><br />{$getItem['description']}<br /><b>Power: {$getItem['power']}</b></span>";
$count++;
}*/
print "</div>";
if($count == 6) {
$count = 0;
}
}
}
I guess you are looking for something like this?
public static function DisplayInv($user) {
$user = users::lookup($user);
$sql = mysql_query("SELECT * from `inventory` where `userid`='{$user['id']}'");
$limit = 6;
$count = 0;
print "<div class='row-fluid show-grid'>";
while($items = mysql_fetch_array($sql)) {
$getItem = self::ItemInfo($items['itemid']);
print "<span class='span2'><b>{$getItem['name']}</b><br />{$getItem['description']}<br /><b>Power: {$getItem['power']}</b></span>";
if($count == $limit){
print "</div><div class='row-fluid show-grid'>";
$count = 0;
}else{
$count++;
}
}
print "</div>";
}

split images from array

i am getting links from a database and want to display the images but break line every 5 images. i can display images but need help, I'm sure its an if statement but don't know how to write it. i need to display
image1,image2,image3,image4,image5 break
image6,image7,image8,image9,image10 break
and so on, i have a total of 100 images
<?php
include('connect.php');
$query = "SELECT * FROM `image`";
$result = mysql_query($query);
$pics = array();
while($row = mysql_fetch_array($result)){
$pics[] = "\"".$row['src']."\"";
}
foreach($pics as $show){
echo "<img src=".$show.">";
}
?>
You can use another variable to count the entries
$count=0;
foreach($pics as $show){
echo "<img src=".$show.">";
if( $count % 5 == 0 ) echo "<br>";
$count++;
}
$count = 1;
foreach($pics as $show){
if($count < 6)
{
echo '<img src="'.$show.'">';
$count++;
}
else
{
echo '<br><img src="'.$show.'">';
$count = 1;
}
}

php echo variable1, pause and echo variable 2 then echo the rest of variable1

let's say that i have this simplyfied code:
$sql = dbquery("SELECT * FROM videos WHERE views > 4 ORDER BY id DESC LIMIT 0,10 ");
while($row = mysql_fetch_array($sql)){
$url = $row["url"];
$title = $row["title"];
$list ='<div><a href="'.$url.'" >'.$title.'</a></div>';
$ad ='<div>something here</div>';
}
echo $list;
instead to display a list of 10 divs, i want to echo 5 divs from $list, echo $ad then echo the rest of the $list
How can i do this?
Later edit :
First problem solved thanks to Michael.
Now, i have a problem with my template, and i don't know how can i add to every X number of $list divs, class="nomar"?
You can use a counter $i
$sql = dbquery("SELECT * FROM videos WHERE views > 4 ORDER BY id DESC LIMIT 0,10 ");
$i = 1;
// Use mysql_fetch_assoc() rather than mysql_fetch_array()!
while($row = mysql_fetch_assoc($sql)){
$url = $row["url"];
$title = $row["title"];
// Change the list class on a certain number...
if ($i == 3) {
$list_class = "normal";
}
else $list_class = "some-other-class";
// Incorporate the new class
$list ='<div class="' . $list_class . '"><a href="'.$url.'" >'.$title.'</a></div>';
// Output $list
echo $list;
// Increment your counter
$i++;
// Output $ad when you reach 5
// This only happens once. Afterward, $list continues to print.
if ($i == 5) {
$ad ='<div>something here</div>';
echo $ad;
}
}

Categories