• We just launched and are currently in beta. Join us as we build and grow the community.

Form Inside While Loop [fixed], Simple Dynamic Posting and Comment using AJAX/Jquery

nibaoxi

Insider Threat Tester
N Rep
0
0
0
Rep
0
N Vouches
0
0
0
Vouches
0
Posts
110
Likes
172
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 400 XP
I have created another tutorial on how to create a dynamic posting and comment using AJAX/JQuery. In this tutorial, you will learn how to create a form inside a while loop in PHP. This tutorial will not give you a good desing but will give you idea on creating a simple posting and commenting.

Creating our Database

First and most important step is for us to create our database. This will serve as our storage for our data.
1. Open phpMyAdmin.
2. Click databases, create a database and name it as "fb_db".
3. After creating a database, click the SQL and paste the below code. See image below for detailed instruction.

  1. CREATE

    TABLE

    `comment`

    (
  2. `commentid`

    INT

    (

    11

    )

    NOT

    NULL

    AUTO_INCREMENT

    ,
  3. `postid`

    INT

    (

    11

    )

    NOT

    NULL

    ,
  4. `userid`

    INT

    (

    11

    )

    NOT

    NULL

    ,
  5. `comment_text`

    VARCHAR

    (

    200

    )

    NOT

    NULL

    ,
  6. `comment_date`

    datetime NOT

    NULL

    ,
  7. PRIMARY

    KEY

    (

    `commentid`

    )
  8. )

    ENGINE=

    InnoDB DEFAULT

    CHARSET=

    latin1;

  1. CREATE

    TABLE

    `post`

    (
  2. `postid`

    INT

    (

    11

    )

    NOT

    NULL

    AUTO_INCREMENT

    ,
  3. `userid`

    INT

    (

    11

    )

    NOT

    NULL

    ,
  4. `post_text`

    VARCHAR

    (

    200

    )

    NOT

    NULL

    ,
  5. `post_date`

    datetime NOT

    NULL

    ,
  6. PRIMARY

    KEY

    (

    `postid`

    )
  7. )

    ENGINE=

    InnoDB DEFAULT

    CHARSET=

    latin1;

  1. CREATE

    TABLE

    `user`

    (
  2. `userid`

    INT

    (

    11

    )

    NOT

    NULL

    AUTO_INCREMENT

    ,
  3. `username`

    VARCHAR

    (

    30

    )

    NOT

    NULL

    ,
  4. `password`

    VARCHAR

    (

    30

    )

    NOT

    NULL

    ,
  5. `your_name`

    VARCHAR

    (

    60

    )

    NOT

    NULL

    ,
  6. PRIMARY

    KEY

    (

    `userid`

    )
  7. )

    ENGINE=

    InnoDB DEFAULT

    CHARSET=

    latin1;

database_6_5.png

Inserting our Sample Users

Next, we insert sample users into our database.
1. Click "fb_db" database that we have created.
2. Click SQL and paste the code below.

  1. INSERT

    INTO

    `user`

    (

    `username`

    ,

    `password`

    ,

    `your_name`

    )

    VALUES
  2. (

    'nurhodelta'

    ,

    'neovic09'

    ,

    'neovic'

    )

    ,
  3. (

    'lee'

    ,

    'ann'

    ,

    'leeann'

    )

    ;

Creating our Connection

Next step is to create a database connection and save it as "conn.php". This file will serve as our bridge between our form and our database. To create the file, open your HTML code editor and paste the code below after the tag.

  1. <?php

  2. //MySQLi Procedural
  3. $conn

    =

    mysqli_connect

    (

    "localhost"

    ,

    "root"

    ,

    ""

    ,

    "fb_db"

    )

    ;
  4. if

    (

    !

    $conn

    )

    {
  5. die

    (

    "Connection failed: "

    .

    mysqli_connect_error

    (

    )

    )

    ;
  6. }

  7. ?>

Creating our Login Form

Next step is to create our login form with our login code for us to determine our user that we are going to use in posting and commenting. We name this form as "index.php".

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title></title>

  5. </head>
  6. <body>

  7. <?php
  8. // define variables and set to empty values
  9. $Message

    =

    $ErrorUname

    =

    $ErrorPass

    =

    ""

    ;

  10. if

    (

    $_SERVER

    [

    "REQUEST_METHOD"

    ]

    ==

    "POST"

    )

    {

  11. $username

    =

    check_input(

    $_POST

    [

    "username"

    ]

    )

    ;

  12. if

    (

    !

    preg_match

    (

    "/^[a-zA-Z0-9_]*$/"

    ,

    $username

    )

    )

    {
  13. $ErrorUname

    =

    "Space and special characters not allowed but you can use underscore(_)."

    ;
  14. }
  15. else

    {
  16. $fusername

    =

    $username

    ;
  17. }

  18. $fpassword

    =

    check_input(

    $_POST

    [

    "password"

    ]

    )

    ;

  19. if

    (

    $ErrorUname

    !=

    ""

    )

    {
  20. $Message

    =

    "Login failed! Errors found"

    ;
  21. }
  22. else

    {
  23. include

    (

    'conn.php'

    )

    ;

  24. $query

    =

    mysqli_query

    (

    $conn

    ,

    "select * from `user` where username='$fusername

    ' && password='$fpassword

    '"

    )

    ;

  25. if

    (

    mysqli_num_rows

    (

    $query

    )

    >

    0

    )

    {
  26. session_start

    (

    )

    ;
  27. $row

    =

    mysqli_fetch_array

    (

    $query

    )

    ;
  28. $_SESSION

    [

    'userid'

    ]

    =

    $row

    [

    'userid'

    ]

    ;
  29. header

    (

    'location:home.php'

    )

    ;
  30. }
  31. else

    {
  32. $Message

    =

    "Login Failed! User not found"

    ;
  33. }

  34. }
  35. }

  36. function

    check_input(

    $data

    )

    {
  37. $data

    =

    trim

    (

    $data

    )

    ;
  38. $data

    =

    stripslashes

    (

    $data

    )

    ;
  39. $data

    =

    htmlspecialchars

    (

    $data

    )

    ;
  40. return

    $data

    ;
  41. }
  42. ?>

  43. <h2>Login Form</h2>
  44. <p><span class="message">* required field.</span></p>
  45. <form method="post" action="<?php

    echo

    htmlspecialchars

    (

    $_SERVER

    [

    "PHP_SELF"

    ]

    )

    ;

    ?>

    ">
  46. Username: <input type="text" name="username" required>
  47. <span class="message">* <?php

    echo

    $ErrorUname

    ;

    ?>

    </span>
  48. <br><br>
  49. Password: <input type="password" name="password" required>
  50. <span class="message">* <?php

    echo

    $ErrorPass

    ;

    ?>

    </span>
  51. <br><br>
  52. <input type="submit" name="submit" value="Login">
  53. <br><br>
  54. </form>

  55. <span class="message">
  56. <?php
  57. echo

    $Message

    ;
  58. ?>
  59. </span>

  60. </body>
  61. </html>

Next is to create our sample homepage, the place where we can post and comment. Also included in the page, is our jquery and ajax code. We name the page as "home.php".

  1. <?php
  2. session_start

    (

    )

    ;
  3. include

    (

    'conn.php'

    )

    ;

  4. if

    (

    !

    isset

    (

    $_SESSION

    [

    'userid'

    ]

    )

    ||

    (

    trim

    (

    $_SESSION

    [

    'userid'

    ]

    )

    ==

    ''

    )

    )

    {
  5. header

    (

    'location:index.php'

    )

    ;
  6. exit

    (

    )

    ;
  7. }

  8. $userq

    =

    mysqli_query

    (

    $conn

    ,

    "select * from user where userid='"

    .

    $_SESSION

    [

    'userid'

    ]

    .

    "'"

    )

    ;
  9. $user

    =

    mysqli_fetch_assoc

    (

    $userq

    )

    ;
  10. ?>
  11. <!DOCTYPE html>
  12. <html lang = "en">
  13. <head>
  14. <meta charset = "UTF-8" name = "viewport" content = "width=device-width, initial-scale=1"/>
  15. <title></title>
  16. </head>
  17. <body>
  18. <h2>Welcome, <?php

    echo

    $user

    [

    'your_name'

    ]

    ;

    ?>

    <a href="logout.php">Logout</a></h2>
  19. <h2>Timeline</h2>
  20. <div id = "post_form">
  21. <form>
  22. <textarea id = "post" class = "form-control" cols="50" rows="5" placeholder="Post Something..."></textarea><br>
  23. <button type = "button" id = "add_post">POST</button>
  24. </form>
  25. <br>
  26. </div>
  27. <div id = "post_result"></div>
  28. </body>
  29. <script src = "jquery-3.1.1.js"></script>
  30. <script type = "text/javascript">
  31. $(document).ready(function(){

  32. var id= "";
  33. showPost();

  34. $('#add_post').on('click', function(){
  35. if($('#post').val() == ""){
  36. alert('Write a Post first!');
  37. }else{

  38. $post = $('#post').val();

  39. $.ajax({
  40. type: "POST",
  41. url: "add_post.php",
  42. data: {
  43. post: $post,

  44. },
  45. success: function(){
  46. showPost();
  47. }
  48. });
  49. }
  50. });

  51. $(document).on('click', '.add_comment', function(){
  52. var id = $(this).val();
  53. if($('#comment_'+id).val() == ""){
  54. alert('Write a Comment first!');
  55. }
  56. else{
  57. $comment = $('#comment_'+id).val();
  58. $postid = $('#postid_'+id).val();

  59. $.ajax({
  60. type: "POST",
  61. url: "add_comment.php",
  62. data:{
  63. comment: $comment,
  64. postid: $postid,
  65. commented: 1,
  66. },
  67. success: function(){
  68. showComment(id);
  69. }

  70. });

  71. }

  72. });

  73. $(document).on('focus', 'textarea',function(){
  74. $(this).val('');
  75. });

  76. $(document).on('focus', 'input:text',function(){
  77. $(this).val('');
  78. });

  79. $(document).on('click', '.view_comment',function(){
  80. var id = $(this).val();
  81. $('#showComment'+id).show();
  82. showComment(id);
  83. });

  84. $(document).on('click', '.close_comment',function(){
  85. var id = $(this).val();
  86. $('#showComment'+id).hide();
  87. });

  88. });

  89. function showPost(){
  90. $.ajax({
  91. url: 'show_post.php',
  92. type: 'POST',
  93. async: false,
  94. data:{
  95. res: 1
  96. },
  97. success: function(response){
  98. $('#post_result').html(response);

  99. }
  100. });
  101. }

  102. function showComment(id){
  103. $.ajax({
  104. type: "POST",
  105. url: "show_comment.php",
  106. data:{
  107. id: id,
  108. comm_res: 1,
  109. },
  110. success: function(response){
  111. $('#comment_result'+id).html(response);
  112. }
  113. });
  114. }
  115. </script>
  116. </html>

Creating our Add Post Code

Next, we create our add post code that is called with the use of jquery/ajax. We name this as "add_post.php".

  1. <?php
  2. include

    (

    'conn.php'

    )

    ;
  3. session_start

    (

    )

    ;
  4. if

    (

    isset

    (

    $_POST

    [

    'post'

    ]

    )

    )

    {
  5. $post

    =

    addslashes

    (

    $_POST

    [

    'post'

    ]

    )

    ;
  6. mysqli_query

    (

    $conn

    ,

    "insert into `post` (`post_text`, `userid`, `post_date`) values ('$post

    ', '"

    .

    $_SESSION

    [

    'userid'

    ]

    .

    "', NOW())"

    )

    or die

    (

    mysqli_error

    (

    )

    )

    ;
  7. }
  8. ?>

Creating our Show Post Code

Next step is to create our show post code that is also called via our jquery/ajax. We name this as "show_post.php".

  1. <?php
  2. include

    (

    'conn.php'

    )

    ;
  3. if

    (

    isset

    (

    $_POST

    [

    'res'

    ]

    )

    )

    {
  4. $query

    =

    mysqli_query

    (

    $conn

    ,

    "select * from `post` left join `user` on user.userid=post.userid order by `post_date` desc"

    )

    or die

    (

    mysqli_error

    (

    )

    )

    ;
  5. while

    (

    $row

    =

    mysqli_fetch_array

    (

    $query

    )

    )

    {
  6. ?>
  7. <div>
  8. Name: <?php

    echo

    $row

    [

    'your_name'

    ]

    ;

    ?>

    <br>
  9. Date: <?php

    echo

    date

    (

    'M-d-Y h:i A'

    ,

    strtotime

    (

    $row

    [

    'post_date'

    ]

    )

    )

    ;

    ?>

    <br>
  10. Post: <?php

    echo

    $row

    [

    'post_text'

    ]

    ;

    ?>

    <br>
  11. <button type ="button" value="<?php

    echo

    $row

    [

    'postid'

    ]

    ;

    ?>

    " class ="view_comment">Comment</button>
  12. <br><br>
  13. <div id="showComment<?php

    echo

    $row

    [

    'postid'

    ]

    ;

    ?>

    " style="padding-left: 30px; display:none;">
  14. Comments: <br><br>
  15. <div id = "comment_result<?php

    echo

    $row

    [

    'postid'

    ]

    ;

    ?>

    "></div>
  16. <div>
  17. <form>
  18. <input type="text" id="comment_<?php

    echo

    $row

    [

    'postid'

    ]

    ;

    ?>

    " placeholder="Write a comment...">
  19. <input type="hidden" value="<?php

    echo

    $row

    [

    'postid'

    ]

    ;

    ?>

    " id="postid_<?php

    echo

    $row

    [

    'postid'

    ]

    ;

    ?>

    ">
  20. <button type = "button" value="<?php

    echo

    $row

    [

    'postid'

    ]

    ;

    ?>

    " class ="add_comment">Write</button> <button type="button" value="<?php

    echo

    $row

    [

    'postid'

    ]

    ;

    ?>

    " class ="close_comment">Close</button>
  21. </form>
  22. <br>
  23. </div>
  24. </div>

  25. </div>
  26. <br>
  27. <?php
  28. }
  29. }
  30. ?>

Creating our Add Comment Code

Next we create our add comment code. We name this as "add_comment.php".

  1. <?php
  2. include

    (

    'conn.php'

    )

    ;
  3. session_start

    (

    )

    ;
  4. if

    (

    isset

    (

    $_POST

    [

    'commented'

    ]

    )

    )

    {
  5. $comment

    =

    addslashes

    (

    $_POST

    [

    'comment'

    ]

    )

    ;
  6. $id

    =

    $_POST

    [

    'postid'

    ]

    ;
  7. mysqli_query

    (

    $conn

    ,

    "insert into `comment` (postid, userid, comment_text, comment_date) values ('$id

    ', '"

    .

    $_SESSION

    [

    'userid'

    ]

    .

    "', '$comment

    ', NOW())"

    )

    or die

    (

    mysqli_error

    (

    )

    )

    ;
  8. }
  9. ?>

Creating our Show Comment Code

Next step is to create our show comment code that is call via our jquery/ajax. We name this as "show_comment.php".

  1. <?php
  2. include

    (

    'conn.php'

    )

    ;
  3. if

    (

    isset

    (

    $_POST

    [

    'comm_res'

    ]

    )

    )

    {
  4. $id

    =

    $_POST

    [

    'id'

    ]

    ;
  5. $query

    =

    mysqli_query

    (

    $conn

    ,

    "select * from `comment` left join `user` on user.userid=comment.userid where postid='$id

    ' order by comment_date asc"

    )

    or die

    (

    mysqli_error

    (

    )

    )

    ;
  6. while

    (

    $row

    =

    mysqli_fetch_array

    (

    $query

    )

    )

    {
  7. ?>
  8. <div>
  9. Date: <?php

    echo

    date

    (

    'M-d-Y h:i A'

    ,

    strtotime

    (

    $row

    [

    'comment_date'

    ]

    )

    )

    ;

    ?>

    <br>
  10. User: <?php

    echo

    $row

    [

    'your_name'

    ]

    ;

    ?>

    <br>
  11. Comment: <?php

    echo

    $row

    [

    'comment_text'

    ]

    ;

    ?>
  12. </div>
  13. <br>
  14. <?php
  15. }
  16. }
  17. ?>

Creating our Logout Code

Lastly, we create our logout code. We name this as "logout.php".

  1. <?php
  2. session_start

    (

    )

    ;

  3. session_destroy

    (

    )

    ;
  4. header

    (

    'location:index.php'

    )

    ;

  5. ?>


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,341

323,350

Top