#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2000
    Posts
    5
    Rep Power
    0

    I have a mysql database (id, parent_id subject, body, posted, and user_id). You can add a post and you can answer to a post. In both the cases id auto_increment but I want to have the answer on the same line as the question

    id 1 a question
    id 4 the answer

    Id Parent_id Subject Body
    1 Test Is Freedy Kruger alive
    2 Rock Is Elvis here
    3 2 Rock Elvis has left the bui.
    4 1 test Freedy is gone for now


    how can I get the body for id 4 into the body of id 1

    the code that just print out everything in a table

    $query="select * from $table where(body like'%$name%')order by id";


    $result=mysql_query($query);
    mysql_close();

    $num=mysql_numrows($result);

    if ($num == 0):
    echo "Sorry no hits this time .";

    else:

    if ($result) {
    echo "<table border=1 cellpadding=2 width=650>";
    echo "<tr><td align=middle><b>Id</b></td><td align=middle><b>Parent_id</b></td>";
    echo "<td align=middle><b>Subject</b></td><td align=middle><b>Body</b></td>
    <td align=middle><b>posted<b/></td><td align=middle><b>User_id</b></td>";

    while ($r = mysql_fetch_array($result)) {
    $id = $r["id"];
    $parent_id = $r["parent_id"];
    $subject =$r["subject"];
    $body =$r["body"];
    $posted =$r["posted"];
    $user_id =$r["user_id"];

    echo "<tr><td align=middle>$id</td><td align=middle>$parent_id</td>";
    echo "<td align=middle>$subject</td><td align=middle>$body</td>";
    echo "<td align=middle>$posted</a></td><td align=middle>$user_id</a></td>";

    }
    } else { echo "No data."; } mysql_free_result($result);
    endif;
    ?>

    regards
    Hazze

  2. #2
  3. No Profile Picture
    Apprentice Deity
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Jul 1999
    Location
    Niagara Falls (On the wrong side of the gorge)
    Posts
    3,237
    Rep Power
    18
    First, you should set the parent_id to 0 if there is no parent. (makes things a bit neater). Then you need to write a recursive function (assumes you are connected and database is selected)

    <?
    function display($id,$tab)
    {
    $result=mysql_query("select * from $table where parent_id=$id");
    while ($data=mysql_fetch_array($result))
    {
    for ($i=0;$i<$tab;$i++)
    {
    print "----";
    }
    print "<font size=+1 color=blue>$data[subject]</font> ";
    print " &nbsp; $data[body]<br>n";
    display($data[id],$tab+1);
    }
    }

    display(0,0);

    ?>

    This is the easiest way and should work fine (although this is NOT tested code, it may need debugging) for smaller tables (less than 10000 entries) and/or low volume sites (less then 10 simultaneous hits).

IMN logo majestic logo threadwatch logo seochat tools logo