I have created a function which is using recursion to find out childs of Given User. as shown below :
function recursionFunc($param) {
$q = "select cust_id,amount,position from testtab where parent_id = $param";
$res = mysql_query($q);
static $i = 0;
while ($row = mysql_fetch_assoc($res)) {
$i++;
recursionFunc($row['cust_id']);
}
return array('totalChild'=>$i);
}
There are two cases:
I want to call recursionFunc() for each user i am having
Recursion will be done in order to find childs of a user.
Now i want to call this function in while loop in order to fetch childs of all user i am having.
Since i am using static variable $i to store the value of childs.
Now when function will be called for the first user it returns correct value of childs but return wrong value in all other cases.
AS show Below
$cutData = "select cust_id from testtab";
$ress = mysql_query($cutData);
while ($raw = mysql_fetch_assoc($ress)) {
$response = recursionFunc($raw['cust_id']);
echo '<pre>'.$raw['cust_id'];
print_r($response);
echo '<br>';
}
Outputs
1Array ( [totalChild] => 7 ) 2Array ( [totalChild] => 10 ) 3Array ( [totalChild] => 12 )
It will be great if you can help me .
Thanks in advance.
Related
I have a table containing user id with left node and right node (Both are which user id). I am trying to create a function to count all the right nodes and total nodes of a particular user id in PHP.
The Code I have written till now which is always returning 0 :
function allcount($id) //Function to calculate all children count
{
$sqlz = "SELECT * FROM user_transaction_details WHERE user_id = '$id'";
$execsql = mysqli_query($conn,$sqlz);
$array = mysqli_fetch_array($execsql);
echo $sqlz;
(array_count_values($array));
$count = 0;
echo $array['l_node'];
if(!empty($array['l_node']))
{
$count += allcount($array['l_node']) +1;
}
if(!empty($array['r_node']))
{
$count += allcount($array['r_node']) +1;
}
return $count;
}
Here is the table structure :
Table Structure
Can anybody please help.
You need to pass $conn as an argument or declare it as global inside the function, because otherwise it is not available inside the function.
Iam trying with the json_encoding for about two hours but iam not getting the output as required. Actually this is a requirement for the mobile application developer who is asking in the format which i will explain here.The code below is what i have tried:
include_once("class_connection.php");
//Getting the Parent Category
$sqlStr = mysql_query("select catname , id from `category` where `parentid`='0'");
$jsonArray = array();
while ($fetchStr = mysql_fetch_assoc($sqlStr)) {
$jsonArray[] = array("ParentCategory" => $fetchStr["catname"]);
$id = $fetchStr['id'];
//Getting child categories from the above parent
$sqlChildStr = mysql_query("SELECT catname,id,parentid FROM `category` where `parentid`='$id'");
while ($fetchchildStr = mysql_fetch_assoc($sqlChildStr)) {
$jsonArray[] = array("ChildCategory" => $fetchchildStr["catname"]);
}
}
echo json_encode(array("JsonOutput" => $jsonArray)) . "<br />";
The Output is :
"JsonOutput":[{"ParentCategory":"Animals"},{"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"},
{"ParentCategory":"Art"},{"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"},{"ChildCategory":"Abstract"}]}
Here , in the above output the parent category array is empty without its child category array. I want to store all the child category array in its parent category array and finally i have to store both parent and child category into the JsonOutput array so i want the output as
"JsonOutput":[{
"ParentCategory":"Animals" : [{
{"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"}
]}
"ParentCategory":"Arts" : [{
{"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"}, {"ChildCategory":"Abstract"}
]}
]}
You probably need to do this (only the important bits are shown):
$jsonArray = array();
while ($parentCat = mysql_fetch_assoc($sqlStr)) {
$temp = array(
"ParentCategory" => $parentCat["catname"]
);
while ($childCat = mysql_fetch_assoc($sqlChildStr)) {
$temp["ChildCategory"][] = array(
"ChildCategory" => $childCat["catname"]
);
}
$jsonArray[] = $temp;
}
I used a temporary variable for storing and manipulating the parent category. This gets added to the main array at the end of loop.
Please use the following codes, give the index inside the while loop...
$jsonArray = {};
while ($fetchStr = mysql_fetch_assoc($sqlStr)) {
//$jsonArray[] = array("ParentCategory" => $fetchStr["catname"]);
$id = $fetchStr['id'];
//Getting child categories from the above parent
$sqlChildStr = mysql_query("SELECT catname,id,parentid FROM `category` where `parentid`='$id'");
while ($fetchchildStr = mysql_fetch_assoc($sqlChildStr)) {
$jsonArray["ParentCategory"][$fetchStr["catname"]] = array("ChildCategory" => $fetchchildStr["catname"]);
}
}
echo json_encode(array("JsonOutput" => $jsonArray)) . "<br />";
I open my sq3d fine, but when I try to do a SELECT on one of my tables it seems to not return the results I excpect. Here is the php code:
$buildingArray = array();
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Database.s3db');
}
}
$db = new MyDB();
$query1 = "SELECT * FROM tbl_uploadData";
$result1 = $db->query($query1);
$u = $result1->fetchArray();
echo "<br/>Size of u: ".sizeOf($u)."<br/>";
for($i=0; $i<sizeOf($u); $i++){
echo "<br/>Items: ".$u[$i]."<br/>";
}
This is what is in my Database:
tbl_uploadData : b_id - 1,2,3,4 : where 1,2,3,4 are the items within the fields, b_id the field name and tbl_uploadData the table.
I expect to get 1, 2, 3 and 4 to return in the fetchArray()
All i get in return is:
Size of u: 2
Items: 1
Notice: Undefined offset: 1 in C:\xampp\htdocs\PHPexcel\Tests\StrategicExcel.php on line 72
Items:
Here is the solution, as spaced monkey mentioned, fetchArray() only returns one result at a time. So by adding a while loop and a couple of references to my b_id, it should work. I've modified my code to:
$databaseName = "Database.s3db";
$db2 = new SQLite3($databaseName);
$sql = "SELECT b_id FROM tbl_uploadData";
$result = $db2->query($sql);//->fetchArray(SQLITE3_ASSOC);
$row = array();
$i = 0;
while($res = $result->fetchArray(SQLITE3_ASSOC)){
if(!isset($res['b_id'])) continue;
$row[$i]['b_id'] = $res['b_id'];
$i++;
}
print_r($row);
Hope this helps if anyone comes across this problem in the future, TY
fetchArray() only gets 1 row at a time, you need to call it for every row. http://uk3.php.net/manual/en/function.sqlite-fetch-array.php
You should be able to:
while ( $u = $result1->fetchArray() ) {
echo "<br/>Items: ".$u['b_id']."<br/>";
}
I don't know why sizeof($u) is returning 2 though.
I have a table like this:
id
name
parent_id
I then want to select certain rows based on their id, so something like this:
SELECT *
FROM TABLE
WHERE id IN ('1', '5', '8', '9', '35')
I want to, from this query, also show the parent/child relationship, like:
id parent
-----------
1 0
5 1
8 0
9 8
35 9
So the final output would look something like this:
1
--5
8
--9
----35
Do I do this outside of mysql, i have tried using arrays, but can't figure it out, or
Do I do it inside MYSQL, which i don't know how to do that either.
Here is what I was able to come with which seems to be working great.
PS-Sorry about the formatting, can't figure it out :( (fixed?)
I grab my parent_id and id from MYSQL and put it into an arraly where the array keys are the id's and the values are the parents, so with in the while loop for mysql, something like this: $testarray[$id] = $parent_id;
Then I run it through the functions below, and it orders it just how I need it.
function retrieveSubTree($parent, $myarray) {
$tempArray = $myarray;
$array = array();
//now we have our top level parent, lets put its children into an array, yea!
while ($child = array_search($parent, $tempArray)) {
unset($tempArray[$child]);
//now lets get all this guys children
if (in_array($child, $tempArray)) {
$array[$child] = retrieveSubTree($child, $tempArray);
} else {
$array[$child] = true;
}
}//end while
return (!empty($array)) ? $array : false;
}
function retrieveTree($myarray) {
$array = array();
$counter = 0;
foreach ($myarray as $key => $value) {
$child = $key;
$parent = $value;
//if this child is a parent of somebody else
if (in_array($child, $myarray) && $parent != '0') {
while ($myarray[$parent] != '' && $myarray[$parent] != '0') {
$newparent = $myarray[$parent];
$parent = $newparent;
}
if (!array_key_exists($parent, $array)) {
$array[$parent] = retrieveSubTree($parent, $myarray);
}
} else {
//now make sure they don't appear as some child
if (!array_key_exists($parent, $myarray)) {
//see if it is a parent of anybody
if (in_array($child, $myarray)) {
$array[$child] = retrieveSubTree($child, $myarray);
} else {
$array[$child] = true;
}
}//end if array key
}//end initial in array
}//end foreach
return (!empty($array) ? $array : false);
}
$test = array(
'1'=>'15',
'2'=>'1',
'3'=>'1',
'4'=>'0',
'5'=>'0',
'6'=>'4',
'7'=>'6',
'8'=>'7',
'9'=>'2',
'10'=>'9'
);
print_r(retrieveTree($test));
Without changing your table structure, this requires recursion, which MySQL does not support. You'll have to do it elsewhere. You can write a recursive function in PHP to use, for example, breadth-first search to build your array. Here it looks like you are using parent_id of 0 to denote a top-level object. You can search over your results, and add to your array every object whose parent is zero, which will give you an array with 1 and 8. Then you can recurse: find all the results with a parent of 1, and add that as a subarray to 1; then find all the results with a parent of 8 and add those as a subarray of 8. Continue doing this for each level until you've run out of results.
As other posters pointed out, you can do this natively in MySQL if you can change the table structure.
I have this code here within a class:
function getRolePerms($role)
{
if (is_array($role))
{
$roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC";
} else {
$roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC";
}
var_dump($roleSQL);
$this->database->dbquery($roleSQL);
$perms = array();
while($row = $this->database->result->fetch_assoc())
{
$pK = strtolower($this->getPermKeyFromID($row['permID']));
var_dump($pK);
if ($pK == '') { continue; }
if ($row['value'] === '1') {
$hP = true;
} else {
$hP = false;
}
$perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']);
}
return $perms;
}
The var_dump() for $roleSQL is:
SELECT * FROM role_perms WHERE roleID = 1 ORDER BY ID ASC
and for $pK:
Admin
When running the query in the database directly i get a result with 8 rows.
Why is it that the loop does not recognize the multiple rows.
Also if i add the statement:
var_dump($this->database->result->fetch_assoc());
It dumps the array of the first row then the loop does the second row.
Im really baffled,
Please help
The culprit is this line here:
$perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']);
What happens is that all of the 8 rows you expect result in $pK == 'Admin'. When you do $perms[$pK] = array(...), each one of the 8 loop iterations ends up writing to the same array key. In the end, there is only one value in the array.
If you change it to
$perms[] = array(...);
it should work as expected, because each iteration will add a new array element with a unique integer key.
Side note:
Avoid doing this:
$roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) ...
Since roleID surely is an integer, use the right tool for the job: intval($role).
Lol the answer actually lies outside the loop.
Calling this function $this->getPermKeyFromID($row['permID']) actually override the results from the database as it was using the same database object. I fixed it by storing the results in a separate variable local to that loop.