1

I have a 'Posts' table (containing submitted posts) and a 'Replies' table (containing all replies to all posts) in my database.

If a user replies to a post, I want the row in the database containing the reply to also contain the id of the original post.

Everything is inputting to the database fine, except for the post_id value, which is zero for every entry. How can I fix this?

home.php:

<?php 
 // top_content.php includes the database connection file.
 include "top_content.php";
 // Include our script to convert MySQL timestamp to 'ago' format.
 include "time_ago.php";
 // Create an object for the time conversion functions
 $timeAgoObject = new convertToAgo; 

 include "menu_and_logo.php"; 
 // Query the database for all submitted posts. //
 $sql = "SELECT * FROM Posts ORDER BY date DESC";
 // Store the result in a variable. //
 $res = mysqli_query($db, $sql) or die(mysqli_error); 
 // Check that the result has > 0 rows; that at least one post exists in the database. //
 if(mysqli_num_rows($res) != 0) {
      // The mysqli_fetch_array retrieves and returns the next row of our query, which is then assigned to $row. //
      // Then it executes the echos, and the procedure begins anew. This is how we get the post list. //
      while($row = mysqli_fetch_array($res)) {
           // Set the post_id variable equal to the post_id of each post. //
           $post_id = $row['post_id'];
           $ts = $row['date'];
           $post_title = $row['post_title'];
           $post_creator = $row['post_creator'];
           // Convert Date Time
           $convertedTime = ($timeAgoObject -> convert_datetime($ts));
           // Then convert to 'ago' time 
           $when = ($timeAgoObject -> makeAgo($convertedTime));
           // Display the data of each row. THe while row will execute all posts, creating a list
           // display.
           echo '<div>';
           // The text is set as the post title, and points to post.php?id=*the post_id of the post. //
           // In post.php, we check that $_GET['id'] is set (that the user is visiting post.php?id=some_integer),
           // then query the database for the respective post, and echo the relevant content. //
           echo '<a href="post.php?id='.$post_id.'">'.$post_title.'</a>';
           echo '<p>by <a href = "view_profile.php?user='.$post_creator.'">'.$post_creator.'</a> '.$when.'</p>'; 
           echo '</div>';

      }

 }else {
    echo "There are no posts.";
 }

?>

post.php:

 <!DOCTYPE html>

<?php
 session_start();
 // Include our script to convert MySQL timestamp to 'ago' format.
 include "time_ago.php";
 // Create an object for the time conversion functions
 $timeAgoObject = new convertToAgo; 
 // Iniate connection to the database.
 include "db_connect.php";
 // Check that the user is visiting post.php?id=some_integer).
 if($_GET['id']) {
      // Set the post id as a variable, for convenience.
    $post_id = $_GET['id'];
      // Query the database for the post that corresponds to the post-title link that has been clicked.
      $sql = "SELECT * FROM Posts WHERE post_id = '".$post_id."' ";
      $res = mysqli_query($db, $sql)or die(mysqli_error());
      // Check that there exists a row containing the relevant post id.
      if(mysqli_num_rows($res) != 0)    {
           // Store the current row's array of data as a variable.
           while($row = mysqli_fetch_array($res)) {
                // Set the current row's data as variables.
                $post_title = $row['post_title'];
                $post_content = $row['post_content'];
                $post_creator = $row['post_creator'];
                $ts = $row['date'];
                    // Convert Date Time
                $convertedTime = ($timeAgoObject -> convert_datetime($ts));
                // Then convert to ago time 
                $when = ($timeAgoObject -> makeAgo($convertedTime));
                // Display the relevant post data.
                echo '<h2>'.$post_title.'</h2>';
                echo '<p>Submitted by <a href = "view_profile.php?user='.$post_creator.'">'.$post_creator.'</a> '.$when.'</p><nr><br>';
                echo ''.$post_content.'';    
           }

      }else{
           echo "This post does not exist.";
      }

 }else{
      header("home.php");   
 }

?>
<!-- I've moved the html tags here because the file needs the $post_title     variable before setting the title -->
<html>
<head><title><?php echo ''.$post_title.' - Lboro Maths'; ?></title></head>

<body>
     <!-- #2: The form where users can submit replies to the original post. -->
     <form action="reply_parse.php" method="POST">
          <input type="textarea" name="reply_content" placeholder="Post a reply...">
          <input type="submit" name="submit_reply" value="Reply">
     </form>

</body>
</html>

reply_parse.php:

<?php 
 session_start();

 include "db_connect.php";

 $post_id = $_GET['id'];
 $reply_content = $_POST['reply_content'];
 $reply_creator = $_SESSION['username'];
 $date = date('y-m-d H:i:s');

 if(isset($_POST['submit_reply'])) {

      $sql = "INSERT INTO Replies (post_id, reply_content, reply_creator, reply_date) VALUES ('$post_id', '$reply_content', '$reply_creator', '$date')";
      $res = mysqli_query($db, $sql)or die(mysqli_error);

      header("Location: home.php");

 }else{
      echo "Fail.";
 }

?>
Callum
  • 315
  • 4
  • 18
  • We need to see the code that invokes this code to see the value that ID is getting. – Jose Manuel Abarca Rodríguez May 03 '16 at 19:57
  • Apologies. Is my edit sufficient? – Callum May 03 '16 at 20:06
  • In you browser, right click the web page and choose "Source code". Check if ` – Jose Manuel Abarca Rodríguez May 03 '16 at 20:11
  • Is it indeed getting different values. – Callum May 03 '16 at 20:13
  • 'post_id' in my 'Posts' table is working fine, and each post URL is displaying the post_id. It's just not working for my 'Replies' table. – Callum May 03 '16 at 20:17
  • So is "post.php" getting the right value for `$_GET["id"]`? If you do `echo $_GET["id"];` do you see a valid id? – Jose Manuel Abarca Rodríguez May 03 '16 at 20:21
  • Yes. Is it a problem that my form for replies is not in the same file as the code that inserts the POST data into the database? So essentially, we have: 1) user clicks post link, GET['id'] is set. 2) on post page, user submits reply. 3) the inputted data is sent to reply_parse.php (my first code block). 4) once the code is executed, user is redirected to home.php. – Callum May 03 '16 at 20:27
  • Wait a second : the first code block IS NOT post.php? Then I need to see post.php to check how the ID is sent to reply_parse.php. – Jose Manuel Abarca Rodríguez May 03 '16 at 20:30
  • I've included all the code in my edit. Sorry again, Jose - thanks for your patience. – Callum May 03 '16 at 20:41
  • 1
    You have no "id" field in your form in post.php, and the form is method POST not GET, so "reply_parse.php" is getting NOTHING as "id". I think that's the problem. – Jose Manuel Abarca Rodríguez May 03 '16 at 20:49
  • You were right, thank you very much! I submitted an answer to detail the exact changes I made. – Callum May 03 '16 at 21:25
  • It's slightly off-topic, but please get familiar with what SQL injections are and how to prevent them. Resources: [StackOverflow](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1), [OWASP](https://www.owasp.org/index.php/SQL_Injection) – StephenKing May 03 '16 at 21:38
  • Thanks @StephenKing - some guys on SO have pointed this out to me before. I've taken note, just procrastinating. – Callum May 03 '16 at 21:40

2 Answers2

1

We needed to insert a hidden field and pass to it the variable GET value for 'id'.

Original:

<body>
     <!-- #2: The form where users can submit replies to the original post. -->
     <form action="reply_parse.php" method="POST">
          <input type="textarea" name="reply_content" placeholder="Post a reply...">
          <input type="submit" name="submit_reply" value="Reply">
     </form>
</body>

Fixed:

<body>
     <!-- #2: The form where users can submit replies to the original post. -->
     <?php
         echo "<form action='reply_parse.php' method='POST'>";
         echo "<input type='hidden' name ='post_id' value='$post_id'>";
         echo "<input type='textarea' name='reply_content' placeholder='Post a reply...'>";
         echo "<input type='submit' name='submit_reply' value='Reply'>";
         echo "</form>";
     ?>
</body>
Callum
  • 315
  • 4
  • 18
0

You have no "id" field in your form in post.php, and the form is method POST not GET, so "reply_parse.php" is getting NOTHING as "id". I think that's the problem.