Recursive function causing webpage to go completely blank - php

I'm trying to print a menu with a recursive function. I used examples of code from these questions:
Echo menu tree with recursive function
Create an multidimensional array from a database table
The code seems right to me and is syntactically correct, but I get a blank page as a result. There are no errors, but the HTML following this php isn't showing up either. Does anyone have any thoughts?
$connect = mysqli_connect($db_host,$db_user,$db_password,$db_database)
or die ("Couldn't connect to server: ".mysqli_error());
$query = "SELECT * FROM categories";
$result = mysqli_query($connect,$query)
or die ("Couldn't execute query: ".mysqli_error());
function menuPrint($categories, $parent = 'root', $level = 0)
{
$menuList = '<ul>';
foreach($categories as $index => $category)
{
if($category['Parent'] == $parent)
{
$menuList .= '<li id="'.$category['ID'].'" class="tier'.$level.'">'.$category['Name'];
$check = $this->menuPrint($categories, $category['ID'], $level+1);
if($check != '<ul></ul>')
$menuList .= $check;
$menuList .= '</li>';
}
}
return $menuList . '</ul>';
}
$catgories = array();
while ($row = mysqli_fetch_assoc($result)) {
$categories[] = array(
'ID' => $row['categoryId'],
'Name' => $row['categoryName'],
'Parent' => $row['parentCategory'],
'Disabled' => $row['disabled']
);
}
$menu = $this->menuPrint($categories);
echo $menu;
mysqli_close($connect);

Related

combine three query and get specific error alert

how can i brief this queries?
i want to combine them but get specific error alert and different three variable
<?php
$sql = "SELECT content FROM post where title='tv'";
$sql2 = "SELECT content FROM post where title='radio'";
$sql3 = "SELECT content FROM post where title='net'";
$result = $connection->query($sql);
$result2 = $connection->query($sql2);
$result3 = $connection->query($sql3);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tvPrice = $row['content'];
}
}else{
echo "tv error";
}
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$radioPrice = $row['content'];
}
}else{
echo "radio error";
}
if ($result3->num_rows > 0) {
while($row = $result3->fetch_assoc()) {
$netPrice = $row['content'];
}
}else{
echo "net error";
}
?>
Using the IN() you can return only those rows with a title of 'tv', 'radio' and 'net'. Then add the title to the query selection so you know which results a re which.
Then just amend you code to fetch all the results into a rows array and then check for the entries and report errors accordingly
<?php
// make a connection to the database obviously :)
$sql = "SELECT title, content
FROM post
WHERE title IN('tv', 'radio', 'net')";
$result = $connection->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC);
// better initialise the variables in case you try using them later
$tvPrice = $radioPrice = $netPrice = 0;
foreach ($rows as $row){
if ($row['title'] == 'tv')){
$tvPrice = $row['content'];
}
if ($row['title'] == 'radio') {
$radioPrice = $row['content'];
}
if ($row['title'] == 'net') {
$netPrice = $row['content'];
}
}
if ( $tvPrice == 0 ) echo 'tv error';
if ( $radioPrice == 0 ) echo 'radio error';
if ( $netPrice == 0 ) echo 'net error';
?>
Usually you don't actually need tree (or more) variables; use an array.
<?php
$titles = ['tv', 'radio', 'net'];
// Generate the query
$sql =
"SELECT content, title FROM post WHERE title IN("
. implode(", ", array_map(function( $title ) use( $connection ) {
return '"' . mysqli_real_escape_string($connection, $title) . '"';
}, $titles) )
. ")";
$result = $connection->query($sql);
$prices = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Check for duplicates
if( !empty( $prices[ $row['title'] . 'Price' ] ) )
echo $row['title'] . " has duplicate error";
else
$prices[ $row['title'] . 'Price' ] = $row['content'];
}
}
// Check if we have all desires rows
foreach( $titles as $title )
if( empty( $prices[ $title . 'Price' ] ) )
echo "$title missing error";
// If you really need tree variables instead of array:
extract($prices);

Loop from category to sub category in PHP

We are having a structure like the way you are seeing in below screenshot:
And our database structure looks like this:
Here in database table "PID" is the Parent ID in which 0 = Parent ID. And rest PID is the parent id of same id.
Now we are trying to get all the sub category of "Brand" Or "Footware" so it should show all (sub-sub-category and sub-sub-sub-category) the sub category details under that tree. Can this be done through PHP? any loop or any way?
Thank you!
try this
function fetchCategoryTreeList($parent = 0, $user_tree_array = '') {
global $con;
if (!is_array($user_tree_array))
$user_tree_array = array();
$sql = "SELECT * FROM `location` WHERE 1 AND `parent_id` = $parent ORDER BY id ASC";
$result=$con->query($sql);
if (mysqli_num_rows($result) > 0)
{
$user_tree_array[] = "<ul>";
while ($row =$result->fetch_object())
{
$user_tree_array[] = "<li>". $row->name."</li>";
$user_tree_array = fetchCategoryTreeList($row->id, $user_tree_array);
}
$user_tree_array[] = "</ul><br/>";
}
return $user_tree_array;
}
call function here
$res = fetchCategoryTreeList();
foreach ($res as $r)
{
echo $r;
}
Try like this:
<?php
//connect to mysql and select db
$conn = mysqli_connect('localhost', 'rootuser', 'rootpwd','dbname');
if( !empty($conn->connect_errno)) die("Error " . mysqli_error($conn));
//call the recursive function to print category listing
category_tree(0);
//Recursive php function
function category_tree($catid){
global $conn;
$sql = "select * from category where pid ='".$catid."'";
$result = $conn->query($sql);
while($row = mysqli_fetch_object($result)):
$i = 0;
if ($i == 0) echo '<ul>';
echo '<li>' . $row->category;
category_tree($row->id);
echo '</li>';
$i++;
if ($i > 0) echo '</ul>';
endwhile;
}
//close the connection
mysqli_close($conn);
?>
Hope this will help.
I used this function in my project, it is a recursive function.
/**** GET ALL CATEGORIES FUNCTION *******/
function categoryChild($id, $spacing = '') {
$s = "SELECT * FROM category WHERE parent_cat_id = $id ";
$r = mysql_query($s);
$children = array();
if(mysql_num_rows($r) > 0) {
while($row = mysql_fetch_array($r)) {
$children[$row['category_id']]['category_name'] = $spacing.$row['category_name'];
$children[$row['category_id']]['id'] = $row['category_id'];
$children[$row['category_id']]['child'] = categoryChild($row['category_id'], $spacing . ' ');
}
}
return $children;
}
> /************ GET ALL CATEGORIES FUNCTION****************/
$allcategory = categoryChild(0);
print_r($allcategory);

How can I make a submenu

I have the next database:
I have the below function:
<?php
$connection = mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("database1", $connection) or die(mysql_error());
function loop_array($array = array(), $parent_id = 0)
{
if (!empty($array[$parent_id])) {
echo '<ul>';
foreach ($array[$parent_id] as $items) {
echo '<li>';
echo ''.$items['title'].'';
loop_array($array, $items['id']);
echo '</li>';
}
}
}
function displays_menus_revised()
{
$sql = "SELECT * FROM pages";
$query = mysql_query($sql) or die(mysql_error());
$array = array();
if (mysql_num_rows($query)) {
while ($rows = mysql_fetch_array($query)) {
$array[$rows['parent_id']][] = $rows;
}
loop_array($array);
}
}
?>
My problem is the funtion show the records like in the left picture. I want the function to show the records like in the right picture. Can you tell me where is the problem? What i must change that the function show records like in the right picture? Thanks.
So nice code, with such a small slip. Only the closing 'ul' is missing.
function loop_array($array = array(), $parent_id = 0)
{
if (!empty($array[$parent_id])) {
echo '<ul>';
foreach ($array[$parent_id] as $items) {
echo '<li>';
echo ''.$items['title'].'';
loop_array($array, $items['id']);
echo '</li>';
}
echo '</ul>';
}
}

Display List of Moodle 2.4 Courses for a user Outside of Moodle

I am trying to create a page where it displays a bullet list of Course Title and link to any courses that user is teacher of for Moodle 2.4.
I found this code here and it works for displaying Moodle course categories but not the courses for a user. I am not a programmer so any help would be very appreciated.
<?php
$con = mysql_connect("localhost","moodle","moodle");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moodle", $con);
$result = mysql_query("SELECT name AS COURSE_NAME,parent FROM mdl_course_categories");
if (isset($result)!=1) {
$message = 'Invalid query: ' . mysql_error() . "\n";
}
echo "<p> The courses taught are: </p>";
///Display Course Categories
$query_catetories = mysql_query('SELECT cc.id, cc.parent, cc.name FROM mdl_course_categories cc ');
$categories = mysql_fetch_all($query_catetories);
$tmp_categories = array();
foreach ($categories AS $row) {
$row['id'] = (int) $row['id'];
$row['parent'] = (int) $row['parent'];
if (!$tmp_categories[$row['parent']])
$tmp_categories[$row['parent']] = array();
$tmp_categories[$row['parent']][] = $row;
}
$course_catetories = buildNode($tmp_categories);
echo '<ul>';
foreach ($course_catetories as $course_catetory) {
print_category_child($course_catetory);
}
echo '</ul>';
function print_category_child($category) {
echo '<li>' . $category['name'];
if (array_key_exists('children', $category)) {
echo '<ul>';
foreach ($category['children'] as $child) {
print_category_child($child);
}
echo '</ul>';
}
echo '</li>';
}
function buildNode($inputArray, $parent = 0) {
$return = array();
foreach ($inputArray[$parent] AS $key => $row) {
if (#$inputArray[$row['id']]) {
$row['children'] = buildNode($inputArray, $row['id']);
}
$return[] = $row;
}
return $return;
}
function mysql_fetch_all($result) {
$all = array();
while ($all[] = mysql_fetch_assoc($result)) {
}
return array_filter($all);
}
///END Course Display
?>'`
Look at your Mysql query :
$result = mysql_query("SELECT name AS COURSE_NAME,parent FROM mdl_course_categories");
Your results are a list of categories' names from the table "mdl_course_categories".
If you want to display a list of courses names, do it using the right table "mdl_course". It may be something like :
mysql_select_db("moodle", $con);
$result = mysql_query("SELECT id, fullname FROM mdl_course WHERE category = "your_course_category_here");
while($row = mysql_fetch_array($result)){
echo $row[0];
echo "<br>";
echo $row[1];
}

Displaying Moodle database data as ul li using php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Nested array. Third level is disappearing
I kinda have a problem here with displaying moodle database data as ul li form using php.
I want to display all the categories of courses, not courses, in their proper nested form as ul li.
The table I'm working on is mdl_course_categories.
Whenever the php script runs, the list must be updated dynamically
The code looks as shown:
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moodle19", $con);
$result = mysql_query("SELECT name AS COURSE_NAME,parent FROM mdl_course_categories");
if (isset($result)!=1) {
$message = 'Invalid query: ' . mysql_error() . "\n";
}
echo "<p> The courses taught are: </p>";
while ($row = mysql_fetch_array($result)) {
$b=$row['COURSE_NAME'];
$c=$row['parent'];
// $a=mysql_query("Select id from mdl_course_categories");
// $condition=mysql_query("SELECT name AS COURSE_NAME FROM mdl_course_categories WHERE parent='0'");
if ($c==0) {
echo "<ul>
<li>" .$b. "</li>
</ul>";
}
else {
echo "<ul>
<li>" .$b. "</li>
</ul>";
$result1 = mysql_query("SELECT name AS COURSE_NAME FROM mdl_course_categories WHERE depth!='1'");
while ($row1 = mysql_fetch_array($result1)) {
$b1=$row1['COURSE_NAME'];
echo "<ul>
<li>" .$b1. "</li>
</ul>";
}
}
}
?>
I have confusion in understand what is going wrong?
I think this will helpful for you -
$query_catetories = mysql_query('SELECT cc.id, cc.parent, cc.name FROM mdl_course_categories cc ');
$categories = mysql_fetch_all($query_catetories);
$tmp_categories = array();
foreach ($categories AS $row) {
$row['id'] = (int) $row['id'];
$row['parent'] = (int) $row['parent'];
if (!$tmp_categories[$row['parent']])
$tmp_categories[$row['parent']] = array();
$tmp_categories[$row['parent']][] = $row;
}
$course_catetories = buildNode($tmp_categories);
echo '<ul>';
foreach ($course_catetories as $course_catetory) {
print_category_child($course_catetory);
}
echo '</ul>';
function print_category_child($category) {
echo '<li>' . $category['name'];
if (array_key_exists('children', $category)) {
echo '<ul>';
foreach ($category['children'] as $child) {
print_category_child($child);
}
echo '</ul>';
}
echo '</li>';
}
function buildNode($inputArray, $parent = 0) {
$return = array();
foreach ($inputArray[$parent] AS $key => $row) {
if (#$inputArray[$row['id']]) {
$row['children'] = buildNode($inputArray, $row['id']);
}
$return[] = $row;
}
return $return;
}
function mysql_fetch_all($result) {
$all = array();
while ($all[] = mysql_fetch_assoc($result)) {
}
return array_filter($all);
}
Thanks

Categories