PHP HOW TO CREATE A Forum BASIC(english)

some help & tips

PHP HOW TO CREATE A Forum BASIC(english)

Postby RAD on Fri Sep 01, 2006 3:16 am

PHP HOW TO CREATE A Forum

Before beginning anything, it should be known that raliser a beautiful forum is not a really simple opration.
On the other hand, with a little work and especially much rflexion, one can be able to do something of sympathetic nerve in relatively little time.

Indeed, let us rflchissons two minutes the following question:

Of how much Web pages (and which are their functions) need us for raliser a forum?

After a rapid rflexion, one can say that one will need:
- a banner page O one will see all the subjects of the forum ( index.php )
- a page of reading O one will be able to read the diffrents messages composing a subject ( lire_sujet.php )
- a page containing a form for insrer a new subject ( insert_sujet.php )
- a page containing a form for insrer a rponse a subject ( insert_reponse.php )

What makes us a total of 4 crire pages.

Another question:

How many tables SQL do we need for raliser our forum?

One can galement say that one will need 2 tables:
- a table containing the subjects (which one will name forum_sujets )
- a table including/understanding the rponses these diffrents prone (that one will name forum_reponses )

We ask maintaining which are the attributes which compose our tables.

The table forum_sujet will comprise:
- an attribute id (of type INT with an option AUTO_INCREMENT ) which will reprsentera the primary education Cl of our table, which will enable us to distinguish all the subjects from our forum (each subject will have one id diffrent).
- an attribute author of type VARCHAR who will comprise the name of the person who has post this subject.
- an attribute titrate of type text who will correspond to the title of the subject.
- an attribute date_derniere_reponse of type datetime who will allow us connatre the date of the dernire rponse of this subject (and it to put this subject in tte in posting).
Indeed, in the majorit of the forums, when one rpond a subject, this one places oneself then always automatically in tte when the forum is posted.

Here then the structure of the table forum_sujets :

Code: Select all
CREATE TABLE forum_sujets (
    id int(6) NOT NULL auto_increment,
    auteur VARCHAR(30) NOT NULL,
    titre text NOT NULL,
    date_derniere_reponse datetime NOT NULL default '0000-00-00 00:00:00',
    PRIMARY KEY  (id)
) TYPE=MyISAM;


The table forum_reponses it will comprise:
- an attribute id (of type INT with an option AUTO_INCREMENT ) which will reprsentera the primary education Cl of our table, which will enable us to distinguish all the rponses each subject from our forum (each rponse will have one id diffrent).
- an attribute author of type VARCHAR comprising the name of the person who has post this rponse.
- an attribute message of type text who corresponds to the message (rponse) which one will post.
- an attribute date_reponse of type datetime who corresponds the date of posting of this rponse.
- an attribute correspondance_sujet of type INT who will allow us to make the connection between the rponses and the subjects of the forum (this attribute will be used to us as joint in order to connatre the subject to which belongs such or such rponse).

Here the structure of the table:
Code: Select all

CREATE TABLE forum_reponses (
    id int(6) NOT NULL auto_increment,
    auteur VARCHAR(30) NOT NULL,
    message text NOT NULL,
    date_reponse datetime NOT NULL default '0000-00-00 00:00:00',
    correspondance_sujet int(6) NOT NULL,
    PRIMARY KEY  (id)
) TYPE=MyISAM;


Veiled dj a good thing of made.
Remain then crire the diffrentes pages.

Let us see the page first of all index.php .
After a rapid rflexion, one can realize that on this page, we will need:
- a bond allowing of insrer a new subject.
- the name of the author of the subject.
- the prone known title.
- the date of the dernire rponse this subject.
- but also the id of this subject (in order to make joint between the two tables).

On this page, one wants galement whom a bond either prsent on the level of each title of subject in order to read the diffrentes rponses belonging each subject (it is L which one will have need for the id).

There will be then (page index.php ):
Code: Select all
<html>
<head>
<title>Index of our forum</title>
</head>
<body>

<!-- one places a bond allowing of accder the page containing the form of insertion of a new subject-->
<a href="./en_insert_sujet.php">Insrer un sujet</a>

<br /><br />

<?php
// one connects our base of give
$base = mysql_connect ('serveur', 'login', 'password');
mysql_select_db ('nom_base', $base) ;

// preparation of the requete
$sql = 'SELECT id, auteur, titre, date_derniere_reponse FROM forum_sujets ORDER BY date_derniere_reponse DESC';

// and one imposes an error message if the requte does not occur well(or die)
$req = mysql_query($sql) or die('Erreur SQL !<br />'.$sql.'<br />'.mysql_error());

// one counts the number of subjects of the forum
$nb_sujets = mysql_num_rows ($req);

if ($nb_sujets == 0) {
    echo 'Aucun sujet';
}
else {
    ?>
    <table width="500" border="1"><tr>
    <td>
    Auteur
    </td><td>
    Titre du sujet
    </td><td>
    Date dernire rponse
    </td></tr>
    <?php
    // one goes scanner all them tuples un par un
    while ($data = mysql_fetch_array($req)) {

    // on decompose la date
    sscanf($data['date_derniere_reponse'], "%4s-%2s-%2s %2s:%2s:%2s", $annee, $mois, $jour, $heure, $minute, $seconde);

    // on affiche les results
    echo '<tr>';
    echo '<td>';

    // on affiche le nom de l'auteur de sujet
    echo stripslashes(htmlentities(trim($data['auteur'])));
    echo '</td><td>';

    // one posts the title of the subject, and on this subject, one insre the bond which will enable us to read the diffrentes rponses of this subject
    echo '<a href="./en_lire_sujet.php?id_sujet_a_lire=' , $data['id'] , '">' , stripslashes(htmlentities(trim($data['titre']))) , '</a>';

    echo '</td><td>';

    // one posts the date of the dernire rponse of this subject
    echo $jour , '-' , $mois , '-' , $annee , ' ' , $heure , ':' , $minute;
    }
    ?>
    </td></tr></table>
    <?php
}

// one free space mmoire allou for this requte
mysql_free_result ($req);
// one closes the connection the base of give.
mysql_close ();
?>
</body>
</html>
[


If you your steps dj died, one go intresser being maintained the page lire_sujet.php allowing to read all the messages of a subject.

Of aprs the code of the page index.php , dj is noticed that grce with the bond put on the title of each subject, one will have a variable $_get['id_sujet_a_lire' ] in the page lire_sujet.php who will correspond the id of the subject of which we wish to read all the messages.

This made explanation, the page lire_sujet.php no problme poses since it quite simply acts of slectionner the rponses of a certain subject and to post them (of which subject? and well quite simply that whose id is gal $_get['id_sujet_a_lire' ] ).

Also, let us not forget to provide a bond towards the page insert_reponse.php allowing us poster of the rponses for the subject which we are reading.

There will be then the following code (page lire_sujet.php ):


Code: Select all
<html>
<head>
<title>Lecture d'un sujet</title>
</head>
<body>

<?php
if (!isset($_GET['id_sujet_a_lire'])) {
    echo 'Sujet non dfini.';
}
else {
?>
    <table width="500" border="1"><tr>
    <td>
    Auteur
    </td><td>
    Messages
    </td></tr>
    <?php
    // one connects our base of give
    $base = mysql_connect ('serveur', 'login', 'password');
    mysql_select_db ('nom_base', $base) ;
   
    // on prpare notre requte
    $sql = 'SELECT auteur, message, date_reponse FROM forum_reponses WHERE correspondance_sujet="'.$_GET['id_sujet_a_lire'].'" ORDER BY date_reponse ASC';

    // on lance la requte (mysql_query) and one imposes an error message if the requte does not occur well(or die)
    $req = mysql_query($sql) or die('Erreur SQL !<br />'.$sql.'<br />'.mysql_error());

    // one goes scanner all them tuples un par un
    while ($data = mysql_fetch_array($req)) {

        // on dcompose la date
        sscanf($data['date_reponse'], "%4s-%2s-%2s %2s:%2s:%2s", $annee, $mois, $jour, $heure, $minute, $seconde);

        // on affiche les rsultats
        echo '<tr>';
        echo '<td>';

        // on affiche le nom de l'auteur de sujet ainsi que la date de la rponse
        echo stripslashes(htmlentities(trim($data['auteur'])));
        echo '<br />';
        echo $jour , '-' , $mois , '-' , $annee , ' ' , $heure , ':' , $minute;

        echo '</td><td>';

        // on affiche le message
        echo nl2br(stripslashes(htmlentities(trim($data['message']))));
        echo '</td></tr>';
    }

    // on libre l'espace mmoire allou pour cette reqte
    mysql_free_result ($req);
    // on ferme la connection  la base de donnes.
    mysql_close ();
    ?>

    <!-- on ferme notre table html -->
    </table>
    <br /><br />
    <!-- one insre a bond which will enable us to add rponses this subject-->
    <a href="./en_insert_reponse.php?numero_du_sujet=<?php echo $_GET['id_sujet_a_lire']; ?>">Rpondre</a>
    <?php
}
?>
<br /><br />
<!-- one insre a bond which will enable us to turn over the reception of the forum-->
<a href="./en_index.php">Retour  l'accueil</a>

</body>
</html>

And veiled:)

Our forum east prsent termin with regard to the posting of the titles of the subjects and the diffrentes rponses.

Now remain to do them 4 dernires pages, those which you to allow us insrer new subjects as well as news rponses.

Let us take the page first of all insert_sujet.php .
This page quite simply proposes a form enabling us to seize our name (the name of the author of the subject), a title of subject as well as a message (either in fact, the first message of our subject).

There will be then the following code (page insert_sujet.php ):


]
Code: Select all
<?php
// on teste si le formulaire a t soumis
if (isset ($_POST['go']) && $_POST['go']=='Poster') {
    // on teste la dclaration de nos variables
    if (!isset($_POST['auteur']) || !isset($_POST['titre']) || !isset($_POST['message'])) {
        $erreur = 'Les variables ncessaires au script ne sont pas dfinies.';
    }
    else {
        // one tests if the variables are not empty
        if (empty($_POST['auteur']) || empty($_POST['titre']) || empty($_POST['message'])) {
            $erreur = At least one of the fields is empty.';
        }

        // if all is good, one can begin insertion in the base
        else {
            // on se connecte  notre base
            $base = mysql_connect ('serveur', 'login', 'password');
            mysql_select_db ('nom_base', $base) ;
           
            // on calcule la date actuelle
            $date = date("Y-m-d H:i:s");

            // prparation de la requte d'insertion (pour la table forum_sujets)
            $sql = 'INSERT INTO forum_sujets VALUES("", "'.addslashes($_POST['auteur']).'", "'.addslashes($_POST['titre']).'", "'.$date.'")';

            // on lance la requte (mysql_query) et on impose un message d'erreur si la requte ne se passe pas bien (or die)
            mysql_query($sql) or die('Erreur SQL !'.$sql.'<br />'.mysql_error());

            // on recupre l'id qui vient de s'insrer dans la table forum_sujets
            $id_sujet = mysql_insert_id();

            // lancement de la requte d'insertion (pour la table forum_reponses
            $sql = 'INSERT INTO forum_reponses VALUES("", "'.addslashes($_POST['auteur']).'", "'.addslashes($_POST['message']).'", "'.$date.'", "'.$id_sujet.'")';

            // on lance la requte (mysql_query) et on impose un message d'erreur si la requte ne se passe pas bien (or die)
            mysql_query($sql) or die('Erreur SQL !'.$sql.'<br />'.mysql_error());

            // on ferme la connexion  la base de donnes
            mysql_close();

            // on redirige vers la page d'accueil
            header('en_Location: index.php');

            // on termine le script courant
            exit;
        }
    }
}
?>
<html>
<head>
<title>Insertion d'un nouveau sujet</title>
</head>

<body>

<!-- one makes point the form towards the treating page give them-->
<form action="en_insert_sujet.php" method="post">
<table>
<tr><td>
<span class="gras">Auteur :</span>
</td><td>
<input type="text" name="auteur" maxlength="30" size="50" value="<?php if (isset($_POST['auteur'])) echo stripslashes(htmlentities(trim($_POST['auteur']))); ?>">
</td></tr><tr><td>
<span class="gras">Titre :</span>
</td><td>
<input type="text" name="titre" maxlength="50" size="50" value="<?php if (isset($_POST['titre'])) echo stripslashes(htmlentities(trim($_POST['titre']))); ?>">
</td></tr><tr><td>
<span class="gras">Message :</span>
</td><td>
<textarea name="message" cols="50" rows="10"><?php if (isset($_POST['message'])) echo stripslashes(htmlentities(trim($_POST['message']))); ?></textarea>
</td></tr><tr><td><td align="right">
<input type="submit" name="go" value="Poster">   
</td></tr></table>
</form>
<?php
// on affiche les erreurs ventuelles
if (isset($erreur)) echo '<br /><br />',$erreur;
?>
</body>
</html>[/color]

A prsent, the systme allowing insrer a new subject, is termin. There remain to us nothing any more but raliser 1 page: that containing the form for insrer a rponse a subject (the page insert_reponse.php ).

Of aprs the page lire_sujet.php , it is noticed that the bond prsent in this page (bond allowing of accder the form of rponses) comprises a variable numero_du_sujet who takes the value of the id subject which one wants rpondre.
By consquent, one will transport this variable in our page insert_reponse.php .

There will be then the following code (page insert_reponse.php ):


[color=green]<?php
// on teste si le formulaire a t soumis
if (isset ($_POST['go']) && $_POST['go']=='Poster') {
    // on teste le contenu de la variable $auteur
    if (!isset($_POST['auteur']) || !isset($_POST['message']) || !isset($_GET['numero_du_sujet'])) {
        $erreur = the variables ncessaires with script are not dfinies.';
    }
    else {
        if (empty($_POST['auteur']) || empty($_POST['message']) || empty($_GET['numero_du_sujet'])) {
            $erreur = At least one of the fields is empty.';
        }
        // if all is good, one can begin insertion in the base
        else {
            // on se connecte  notre base de donnes
            $base = mysql_connect ('serveur', 'login', 'password');
            mysql_select_db ('nom_base', $base) ;

            // on recupere la date de l'instant prsent
            $date = date("Y-m-d H:i:s");

            // prparation de la requte d'insertion (table forum_reponses)
            $sql = 'INSERT INTO forum_reponses VALUES("", "'.addslashes($_POST['auteur']).'", "'.addslashes($_POST['message']).'", "'.$date.'", "'.$_GET['numero_du_sujet'].'")';

            // on lance la requte (mysql_query) et on impose un message d'erreur si la requte ne se passe pas bien (or die)
            mysql_query($sql) or die('Erreur SQL !'.$sql.'<br />'.mysql_error());

            // prparation de la requte de modification de la date de la dernire rponse poste (dans la table forum_sujets)
            $sql = 'UPDATE forum_sujets SET date_derniere_reponse="'.$date.'" WHERE id="'.$_GET['numero_du_sujet'].'"';

            // on lance la requte (mysql_query) et on impose un message d'erreur si la requte ne se passe pas bien (or die)
            mysql_query($sql) or die('Erreur SQL !'.$sql.'<br />'.mysql_error());

            // one closes the connection the base of give
            mysql_close();

            // one redirects towards the page of reading of the subject in progress            header('en_Location: lire_sujet.php?id_sujet_a_lire='.$_GET['numero_du_sujet']);

            // on termine le script courant
            exit;
        }
    }
}
?>

<html>
<head>
<title>Insertion d'une nouvelle rponse</title>
</head>

<body>

<!-- on fait pointer le formulaire vers la page traitant les donnes -->
<form action="en_insert_reponse.php?numero_du_sujet=<?php echo $_GET['numero_du_sujet']; ?>" method="post">
<table>
<tr><td>
<span class="gras">Auteur :</span>
</td><td>
<input type="text" name="auteur" maxlength="30" size="50" value="<?php if (isset($_POST['auteur'])) echo stripslashes(htmlentities(trim($_POST['auteur']))); ?>">
</td></tr><tr><td>
<span class="gras">Message :</span>
</td><td>
<textarea name="message" cols="50" rows="10"><?php if (isset($_POST['message'])) echo stripslashes(htmlentities(trim($_POST['message']))); ?></textarea>
</td></tr><tr><td><td align="right">
<input type="submit" name="go" value="Poster">   
</td></tr></table>
</form>
<?php
if (isset($erreur)) echo '<br /><br />',$erreur;
?>
</body>
</html>


And veiled, our forum east prsent termin:)


What to make moreover?

Indeed, this forum, if you have it test, does not have really a super mouth fun, malgr the fact that it functions perfectly.
For the amliorer, you can for example amliorer largely his prsentation by using beautiful style sheets ( css ).
You can galement test the contents of the variables (see if they are empty or not with the function empty and thus viter that empty messages come pollus your forum).
Or, why not try to make a small management of simleys?

AT your keyboards: :D :twisted: 8) 8)


♠ - ω Comment is CLOSED for This POST ω - ♠
RAD

Image La plus grande erreur que puisse faire un homme est d'avoir peur d'en faire une.
User avatar
RAD
Administrateur - Site Admin
 
Posts: 532
Joined: Thu Aug 31, 2006 12:02 am

Return to WEBMASTER

Who is online

Users browsing this forum: No registered users and 1 guest

cron