1

During my coding I really got stuck into this problem. I ran a foreach loop and for every item I had to get a certain value from a function. But I got only one returned. I could not figure out what was happening. I hope you guys surely will. Below is the short version of my program. Database structure is given at last.

<?php


function opendb() {
    mysql_connect("localhost", "root", "root");
    mysql_select_db("something_db");
}

function sql_query($sql) {
    $datas = array();
    if ($res = mysql_query($sql)) {
        $x = 0;

        while ( $data = mysql_fetch_assoc($res) ) {
            $datas[$x] = $data;
            $x += 1;
        }
    }
    return $datas;
}

function get_parent_id($table, $parent, $cid) {

    // cid=>child id
    $sql = "SELECT * FROM $table WHERE id=$cid";
    $datas = sql_query($sql);
    $pid = $datas[0]['parent'];
    $p_id = $datas[0]['id'];
    if ($pid != 0) {
        get_parent_id($table, $parent, $pid);
    } else {

        return $p_id;
    }
}

opendb();

$datas_pkg = sql_query("SELECT * FROM tbl_packages WHERE 1");
foreach ( $datas_pkg as $data_pkg ) {
    echo $data_pkg['destination_id'] . '-->';
    echo $parent_id = get_parent_id('tbl_destinations', 'parent', $data_pkg['destination_id']);
    echo '<br/>';
}
?>

Database structure..

tbl_destinations

+--------+-------------------------+-----------+ 
| id(int)|destination_name(Varchar)|parent(int)| 
+--------+-------------------------+-----------+

tbl_packages

+-------+---------------------+-------------------+
|id(int)|package_name(varchar)|destination_id(int)|
+-------+---------------------+-------------------+

If I did not clear my question please let me know so that I can help you to help me.

Bikal Basnet
  • 1,639
  • 1
  • 21
  • 31

1 Answers1

1
  if($pid!=0)
  {
            get_parent_id($table,$parent,$pid);

  }

You call the function, but never use its value.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • I think I didn't get it.. Can you please elaborate your answer – Bikal Basnet Nov 12 '12 at 17:29
  • You have a function that executes a SQL query, fetches the result and return it, and then discard the returned value. Don't you want to store it in a variable or do something with it? – Álvaro González Nov 12 '12 at 17:34
  • But, I did used the value that was returned from the function by echoing, didn't I? – Bikal Basnet Nov 12 '12 at 17:46
  • I must be blind. I can't see any `echo` in the four-line excerpt I've quoted. – Álvaro González Nov 12 '12 at 17:49
  • okay!! about that it is a recursive function. It first checks if the parent is 0(Zero) or not.If it is it returns the id of the destination that has parent=0 else it calls the function again until condition 0 is not matched. In my database I do have some destination that has a parent=0 condition – Bikal Basnet Nov 12 '12 at 17:53