Home >Backend Development >PHP Tutorial >Building a website: writing a forum using recursive functions_PHP tutorial
The implementation method of the forum is relatively complicated. As long as you analyze it, the problem will be easily solved. Let's first look at the implementation of the forum. Some people post, and then others follow. This relationship forms a father-son relationship. Generally, a practical forum is written. , as long as this child-father relationship is solved, the forum will be formed.
Let’s take a look at how to complete the forum. First, you must use a database to record this child-father relationship. The general method is to use unique ID numbers to complete it. , the field recording the id number of the parent post is generally recorded with "parentid". When storing the child post, the id number of the parent post is recorded, and the parentid of the parent post is always 0. Take a look at the recording format of the database:
Parent 1 :id:1 | parentid:0
child1:id:2 | parentid:1
child1:id:3 | parentid:2
parent2:id:4 | parentid:0
Child 2:id:5 | parentid:4
Child 2:id:6 | parentid:4
...
The child-parent relationship recorded in the database has been established, and then let’s analyze PHP How to establish this parent-child relationship and add it to the database? First, when a user wants to speak, his post is a parent post, so php can set the parentid to 0. When a user follows a post, php will set the user's post to 0. The id number of the parent post is appended to parentid, so that PHP is completed and the child-parent relationship is established.
The establishment and storage of the child-parent relationship is realized. The next step is to display this relationship. Here is You need to use a recursive function to achieve this, look at the following code:
.....
$result=mysql_query("select * from table where parentid=0");
$num=mysql_numrows( $result);
if (!empty($num)) {
for ($i=0;$i<$num;$i++) {
$parentid=mysql_result($result,$i ,"id");
function showchild($parentid) {
//Add ul control layer into
$result=mysql_query("select * from table where parentid=$parentid");
$numb=mysql_numrows($result);
if (!empty($numb)) {
for ($i=0;$i<$numb;$i++) {
....
$parentid=mysql_result($result,$i,"id");
....
showchild($parentid);
}
....
.. ..
}
....
....
}
showchild($parentid);
....
....
}
....
....
}
The above code is a method of using recursive functions to implement a forum. Of course, this forum is extremely primitive, with functions added to different parts. Code can make this forum gradually stronger. Interested readers may wish to try it themselves.