Recursive function to generate breadcrumbs - php

function createPath($id, $category_tbl, $path) {
$s = "SELECT * FROM ".$category_tbl." WHERE ID = $id";
$r = mysql_query($s);
$row = mysql_fetch_array($r);
if($row['PARENT_ID'] == 0) {
$path .=$row['TITLE'].'-';
}
else {
$path .='-'.$row['TITLE'];
createPath($row['PARENT_ID'],$category_tbl, $path);
}
return $path;
}
It is a recursive function that must generate breadcrumbs. I cannot get it to work properly, it only returns the last TITLE.
the sql table is something like ID, TITLE, PARENT_ID
a PARENT_ID = 0 means the category has no parent,
for any other PARENT_ID, go to that ID, get it's title and add it to the $path variable
I need help to make this work. Alternatives are also welcomed.

Try something like this:
function createPath($id, $category_tbl) {
$s = "SELECT * FROM ".$category_tbl." WHERE ID = $id";
$r = mysql_query($s);
$row = mysql_fetch_array($r);
if($row['PARENT_ID'] == 0) {
return $row['TITLE'];
} else {
return createPath($row['PARENT_ID'],$category_tbl).'-'.$row['TITLE'];
}
}

Looks like you either need to use the value returned by createPath or have $path passed by reference, &$path. One or the other, but not part of each.

Related

How do I detect the last iteration in while loop

I tried doing this first:
$e = 0;
$objectsid = mysql_query("SELECT * FROM xw_char_items WHERE CharId = '$charid' AND ItemCat = 'object' ORDER BY SortOrder ASC");
while($obj = mysql_fetch_array($objectsid)) {
$e++;
if($e==9) break;
$objectsinfo = mysql_query("SELECT * FROM xw_objects WHERE ItemId = '{$obj["ItemId"]}'");
$object = mysql_fetch_array($objectsinfo);
echo "&charid$e={$char["Id"]}";
if($objectsid == end($obj)) {
echo "&intActiveObject=1";
echo "&intObjectsNum=$e";
}
}
Here it never detects the last one. I also tried this:
$e = 0;
$len = count($objectsid));
while($obj = mysql_fetch_array($objectsid)) {
$e++;
if($e==9) break;
$objectsinfo = mysql_query("SELECT * FROM xw_objects WHERE ItemId = '{$obj["ItemId"]}'");
$object = mysql_fetch_array($objectsinfo);
mysql_free_result($objectsinfo);
echo "&charid$e={$char["Id"]}";
if ($e == $len - 1) {
echo "&intActiveObject=1";
echo "&intObjectsNum=$e";
}
}
Here it detects every iteration as the last one.
Does anyone how to make it detect the last iteration?
The $objectsid variable is storing the mysql_result object not the array of your fetched rows. So even if you apply count($objectsid), you will not get the length of your fetched array.
So the right method is to use mysql_num_rows().
So Simply do this $len=mysql_num_rows($objectsid); and the rest will workout as you are expecting. :)

Failing to assign values to array from a loop

I have got this code:
function retrieve_answers($array = array(), $id = null)
{
include(root_path . '\config.php');
if($id == null)
{
$id = $this->question_id;
}
$query = mysqli_query($link, "SELECT * FROM `answers` WHERE `question_id`='$id'");
if(!mysqli_num_rows($query))
{
throw new Exception('Question not found.');
}
/* - Retrieves the answer rows
- Loops through the array
- Indexes the array and assigns the answerID to the index */
else
{
while($result = mysqli_fetch_array($query))
{
for($i=0;$i<mysqli_num_rows($query);$i++)
{
$array[$i] = $result["id"];
}
}
}
}
Which is a part of a class.
What am I trying to do?
I am trying to accept an array as a parameter, and assign values to the array, the values are to be answerIDs which are linked to the question.
The test.php file is here:
<?php
define('root_path', realpath(dirname(__FILE__)));
include(root_path . '\config.php');
require_once(root_path . '\includes\question.class.php');
$q = new Question(3);
$array = array();
$q->retrieve_answers($array);
var_dump($array);
?>
What happens?
When I try to debug by dumping the array, it shows that the array contains nothing:
array(0) { }
I tried to execute the MySQL result through the class to debug, and it does succeed to retrieve the answer IDs, so I'm pretty positive the issue is in the array.
I would happy to get assistance, thanks in advance.
return value in a function like this
function retrieve_answers($array = array(), $id = null)
{
include(root_path . '\config.php');
if($id == null)
{
$id = $this->question_id;
}
$query = mysqli_query($link, "SELECT * FROM `answers` WHERE `question_id`='$id'");
if(!mysqli_num_rows($query))
{
throw new Exception('Question not found.');
}
/* - Retrieves the answer rows
- Loops through the array
- Indexes the array and assigns the answerID to the index */
else
{
$i = 0;
while($result = mysqli_fetch_array($query))
{
$array[$i] = $result["id"];
$i++;
}
return $array;
}
}
and then get it as
$arr = $q->retrieve_answers($array);
var_dump($arr);

get array values with a function in PHP

What is the proper way to create a function to get array values from a query? I am getting "Undefined index: page_title" error.
However I can get the value without function like: echo $row->page_title;
Or echo $query[0]->title;
function get_page($id) {
$db = new DB();
$query = $db->get_rows("SELECT * FROM pages WHERE id = :id ", array('id' => $_GET['id']) );
foreach ($query as $row) {
$page_id = $row->id;
$page_title = $row->title;
}
return $query;
}
$page = get_page(1);
echo $page['page_title'];
here is my database class:
function get_rows($query, $values=array(), $fetchType = FETCH_OBJ)
{
$sth = $this->dbh->prepare($query);
if(is_array($values) && (sizeof($values) > 0))
{
foreach($values as $key=>$val)
{
$key = is_numeric($key) ? ($key + 1) : $key;
$sth->bindValue($key,$val);
}
}
if($sth->execute())
return $sth->fetchAll($fetchType);
}
To make the function reusable, I would rewrite it the following way
function get_page($id, $col) {
$db = new DB();
$query = $db->prepare('SELECT * FROM pages WHERE id = :id');
$query->execute(array(':id' => $id));
$results = $query->fetch(PDO::FETCH_NUM);
return $results[0][$col];
}
$page = get_page(1, 'page_title');
echo $page;
I skipped the foreach as you said that all id's are unique so you should only ever have 1 result
Also it may not be a bad idea to add some error checking to make sure you do get back what you expect from the query and to make sure it is not empty.
Edit: Sorry if the syntax is a little off, dont have anything to test the code against quickly.

Recursive PHP function not returning result

Just a simple function to build breadcrumbs based off a simple database table where there are columns:
id, parent, title
The "parent" column can be 0 for top-level, or the "id" of another row for sub-categories (unlimited depth). All I'm trying to do is have a function that'll help me build breadcrumbs from it, starting from the "id" of the bottom-most category I specify and working its way up to the top parent. Here's what I have:
function getCategoryParents($id=0, $out=array()) {
$id = (int)$id;
if ($id > 0) {
$query = "SELECT * FROM `" .$this->tables['categories']. "` WHERE (`id`=" .$id. ")";
$cat = sqlfetch(sqlquery($query));
array_push($out, $cat);
if ($cat['parent']) {
$this->getCategoryParents($cat['parent'], $out);
} else {
return $out;
}
} else {
return $out;
}
}
But it's not returning anything. But, if I do a print_r($out) from within the function instead of return, ex:
if ($cat['parent']) {
$this->getCategoryParents($cat['parent'], $out);
} else {
echo print_r($out);
}
It outputs the array just fine. But I need to be able to actually work with the array, so I need it returned from the function. I'm sure I'm missing something incredibly small, but I cannot figure it out for the life of me!
Also, I don't want to do a global variable, and also need the info of the category id specified in the initial function call as part of the array as well (as I was trying to do).
Following the suggestions, here's what ended up working:
function getCategoryParents($id=0) {
$out = array();
$id = (int)$id;
if ($id > 0) {
$query = "SELECT * FROM `" .$this->tables['categories']. "` WHERE (`id`=" .$id. ")";
$cat = sqlfetch(sqlquery($query));
array_push($out, $cat);
if ($cat['parent']) {
$out = array_merge($out, $this->getCategoryParents($cat['parent']));
}
}
return $out;
}

PHP Array not being delivered

I have some data in a database column called "gcmregid".
I access this data by calling:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
while ($row = mysql_fetch_array($r)) {
$result = array(
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
Correct me if I'm wrong, but this should deliver an array, due to result = array?
I took this logic from here: Getting Resource id #3 Error in MySql
.Then I thaught using a loop would be helpful, such as:
$userCount = $db->getUserCount(); // counting said table
$registation_ids = array(); // again create array
for($i=0; $i < $userCount; $i++)
{
$gcmRegId = $db->getGCMRegID($selUsers[$i]);
$row = mysql_fetch_assoc($gcmRegId);
//Add RegIds retrieved from DB to $registration_ids
array_push($registation_ids, $row['gcmregid']); // this creates an array consisting of gcmregid s ?
}
It doesn't work either.
Any input would be really appreciated right now...
Thanks
I'm not sure what's going wrong, but if the problem is that it's returning a single item: that's because you keep making a new array with every iteration, discarding the old one. If you want to collect all the rows, make a new array outside of the loop and then add the results to it:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
$result = array();
while ($row = mysql_fetch_array($r)) {
$result[] = array (
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
You should consider working more on how you name your functions. If you are trying to get gcmregid, the method should not say getAllUsers. Anyway, did you try the following:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$row = mysql_fetch_array($query_result);
return $result[0]['gcmregid'];
}
OR if you are trying to get all gcmregid in one shot:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$i=0;
while ($row = mysql_fetch_array($query_result)){
$result[$i++] = $row['gcmregid'];
}
return $result;
}

Categories