1

So, I have this system where you can make a post. So, how it works is, there is an input field, whatever you type in the input field, and click post, it will send to the database as en entry and get posted. The post will be displayed. However, with my current system, after entering something in the input field, and clicking post, the entry gets sent to the database, but the post doesn't actually display. For it to display, you need to refresh the page again, which it displays then, and two entries go to the database.

I don't want this to happen. Right when the user enters text into the input field and clicks post, the post should display on the go, you shouldn't have to refresh for the post to be displayed, and only one entry should be sent to the database, not two. Now, I won't include my database connection and my insert statements, but here is the code to display the post:

<div class="textPost">
  <?php

  $sql = "SELECT * FROM posts";
  $result = mysqli_query($connection, $sql);
  if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {

  ?>
  <div class="textpostFormat">
    // all the displayed post content
  </div>
  <?php

  }
}

  ?>
</div>

Insert Statement (post.php):

<?php

session_start();

// Making Connection To The Database

$dbHost = "localhost";
$dbUser = "root";
$dbPass = "root";
$database = "feed";

$connection = mysqli_connect($dbHost, $dbUser, $dbPass, $database) or die ("Sorry, we could not connect to the database");

// Posting System

if (!empty($_POST['postContent'])) {
  $post = $_POST['postContent'];
  $firstname = $_SESSION['firstname'];
  $lastname = $_SESSION['lastname'];

  $sql = "INSERT INTO posts (firstname, lastname, body, date_posted) VALUES (?, ?, ?, NOW())";
  $stmt = mysqli_stmt_init($connection);
  // nested if statement
  if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo "";
  } else {
    mysqli_stmt_bind_param($stmt, "sss", $firstname, $lastname, $post);
    mysqli_stmt_execute($stmt);
  }
} else {
  echo "";
}

?>

What should I do to resolve this issue? Please help.

  • you are saveing post through AJAX/FORM ? – Pushpendra Kumar Dec 20 '21 at 05:39
  • How do you submit the form? Does that cause the page refresh? From the sound of it does... so we need to see your actual page code. – Jon Dec 20 '21 at 05:41
  • Use redirect in your last line of your php script to refresh your page. – Ali Azimi Dec 20 '21 at 05:42
  • 1
    @AliBabaAzimi How? Could you explain where and what the code would be? –  Dec 20 '21 at 05:45
  • Guys, I don't have any AJAX to prevent or cause page refresh through AJAX. Right now, as suggested by @AliBabaAzimi, I could use redirect in my last line of my PHP script to refresh my page then automatically. So, how could I do that. But also, a limitation is, after that, if I refresh again, won't multiple entries of the same post be sent to the database? –  Dec 20 '21 at 05:51
  • You should implement something called [Post-Redirect-Get](https://stackoverflow.com/questions/10827242/understanding-the-post-redirect-get-pattern). – M. Eriksson Dec 20 '21 at 06:11
  • There are a number of ways to handle this problem. Most people would use ajax, but you aren't going to get a complete tutorial and rewrite of your code to ajax. The simplest pattern in php is to combine your code so that you don't have one script that is form + datatable with a separate script that handles the mysql update , and instead is one script that is form + datatable + post handler. In the script you need to detect at the top if it was submitted to. If so you do the update. In all cases you render the empty form and the table. – gview Dec 20 '21 at 06:27

2 Answers2

0

I think it would be better to share the form codes to which you submit the data. Anyway, I guess you need to redirect after the script is completed. In PHP you can use the header to redirect to a new page as bellow:

index.php

<div class="textPost">

<form method="post" action="post.php">
    <input type="text" name="firstname">
    <input type="text" name="lastname">
    <input type="text" name="postContent">
    <input type="submit">
</form>


<?php

$dbHost = "localhost";
$dbUser = "root";
$dbPass = "root";
$database = "feed";

$connection = mysqli_connect($dbHost, $dbUser, $dbPass, $database) or die("Sorry, we could not connect to the database");


$sql = "SELECT * FROM posts";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
   while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="textpostFormat">
  // all the displayed post content
</div>
<?php
    }
}

?>
</div>

post.php

<?php

session_start();

// Making Connection To The Database

$dbHost = "localhost";
$dbUser = "root";
$dbPass = "root";
$database = "feed";

$connection = mysqli_connect($dbHost, $dbUser, $dbPass, $database) or die ("Sorry, we could not connect to the database");

// Posting System

if (!empty($_POST['postContent'])) {
  $post = $_POST['postContent'];
  $firstname = $_SESSION['firstname'];
  $lastname = $_SESSION['lastname'];

  $sql = "INSERT INTO posts (firstname, lastname, body, date_posted) VALUES (?, ?, ?, NOW())";
  $stmt = mysqli_stmt_init($connection);
  // nested if statement
  if (!mysqli_stmt_prepare($stmt, $sql)) {
    echo "";
  } else {
    mysqli_stmt_bind_param($stmt, "sss", $firstname, $lastname, $post);
    mysqli_stmt_execute($stmt);
    header("Location: /");
    exit();
  }
} else {
  echo "";
}

?>

Please let me know if you needed more instruction.

Ali Azimi
  • 276
  • 3
  • 18
  • Ok where should I add this code? –  Dec 20 '21 at 11:06
  • After your sql statement executed successfully, after mysqli_stmt_execute($stmt), right in your 'else' part. – Ali Azimi Dec 20 '21 at 14:54
  • Ok, I put it there. Didn't work. –  Dec 20 '21 at 15:51
  • in case your main page is index.php, the above code is working. It worked for me, please try it once more. – Ali Azimi Dec 21 '21 at 13:50
  • I tried in my post.php the exact way you did, didn't work. –  Dec 22 '21 at 05:45
  • So the post should be displayed in yourposts.php, but this particular code (like all this insertion stuff) is in another file called post.php, which is the file which you put in the answer. –  Dec 22 '21 at 05:45
  • Suppose you have two files index.php and post.php, and index.php is the file where you want to show all the posts, but post.php is the script that runs once when you click submit button in your form. – Ali Azimi Dec 22 '21 at 07:36
  • if your files are post.php and yourposts.php then you should edit that line like this: 'header(location: /yourposts.php)'. This will go back to your main page after submitting the post. – Ali Azimi Dec 22 '21 at 07:38
  • Yup, I tried that. Didn't work. –  Dec 22 '21 at 10:38
  • Can you share the error? Because it is working for me. – Ali Azimi Dec 22 '21 at 15:47
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/240353/discussion-between-ali-baba-azimi-and-reddy-boi34). – Ali Azimi Dec 22 '21 at 16:07
0

Here is an outline for you of the "one php script/self posting" pattern I described briefly in the comment.

The important thing to understand is that if you have a form with no action, the page will submit to itself. You also need to understand the different HTTP request types: 'GET' vs 'POST' specifically.

Last but not least you have to be clear how HTTP Request/response works. When your page is rendered, and it has a form on it, nothing new happens until you create some sort of event through interaction with the page. If you don't understand how HTTP requests work, I would encourage you to learn about them or you will struggle with web development.

<?php
// somepage.php
session_start();
// db includes etc. here.

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['postContent']) {
   // Move all your database update code here.
   // This will only run if it posted.
}
?>
// Include your HTML header that actually starts your html
<!DOCTYPE html>
<form method="post">
  <input id="postContent" name="postContent" etc.>
</form>
<div class="textPost">
  <?php

  $sql = "SELECT * FROM posts";
  $result = mysqli_query($connection, $sql);
  if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {

  ?>
  <div class="textpostFormat">
    // all the displayed post content
  </div>
  <?php

  }
}

  ?>
</div>
gview
  • 14,876
  • 3
  • 46
  • 51
  • This will still keep adding duplicates if they update the page after a form submission. – M. Eriksson Dec 20 '21 at 07:26
  • @M.Eriksson Yeah. –  Dec 20 '21 at 11:22
  • The page will display the newly updated data after form submission. It does not "refresh" and add duplicates. If you resubmit the form again with the same data, which it will not have on the post, using the back button, you can get a duplicate, but that is a different problem entirely. – gview Dec 21 '21 at 00:15