0

I have a problem which is the user when write in my comments form is insert successfully but when I refresh the page it will insert the last comments again , I read the solution in this link how to stop data automatically insert into database in php

but does not work for me this is my codes I would appreciate for your help :)

file viewhospital.php contain include comments.php file --look at the bottom of the codes--

<?php
include ('header.php');
if(!isset($_GET['hospital_id'])){
    echo '<div class="alert alert-danger" role="alert"><b>You should choose hospital before opening this page!</b></div>';
    include ('footer.php');
    die();
}

include ('setting.php');

$sql = 'select * from hospital where hid = '. $_GET['hospital_id'];

$result = $conn->query($sql) or die(mysql_error($conn));
$hospital = null;

if ($result->num_rows > 0) {
    $hospital = $result->fetch_assoc();
} else {
    die('Could not find hospital!');
}

$sql = 'select * from doctor where hospital_id = '. $_GET['hospital_id'];

$doctor_result = $conn->query($sql) or die(mysql_error($conn));

$conn->close();
?>
  <div class="row">
    <div class="col-md-6">
      <p class="text-center">
        <img src="<?php echo $hospital['image']; ?>" class="img-thumbnail" style="height: 400px;">
      </p>
    </div>
    <div class="col-md-6">
      <p class="text-center">
        <img class="img-thumbnail" src="https://maps.googleapis.com/maps/api/staticmap?center=<?php echo $hospital['location']; ?>&zoom=13&size=400x400&maptype=roadmap&markers=color:blue%7Clabel:S%7C<?php echo $hospital['location']; ?>&key=AIzaSyD59nHXpZgqZwjJvsAcPe2CYcIEWoaQ9yY" style="height: 400px;">
      </p>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12">
      <h1 class="page-header">
<?php echo $hospital['name']; ?>
</h1>
      <p>
        <?php echo $hospital['description']; ?>
      </p>
      <p>
        Address: <?php echo $hospital['address']; ?>
      </p>
      <p>
        Phone: <?php echo $hospital['phone']; ?>
      </p>
      <p>
        <a href="<?php echo $hospital['link1']; ?>">Go To Hospital</a>
      </p>
      <p>
        <a href="<?php echo $hospital['link2']; ?>">Online Appointment</a>
      </p>
    </div>
  </div>
  <!--<div class="row">
    <div class="col-md-12 text-center">
      <div class="btn-group" role="group" aria-label="...">
        <a type="button" class="btn btn-info">Edit</a>
        <a type="button" class="btn btn-danger">Remove</a>
        <a type="button" class="btn btn-primary" href="doctor_form.php?hospital_id=<?php echo $hospital['hid']; ?>">Add Doctor</a>
      </div>
    </div>
  </div>-->
  <div class="row">
    <div class="col-md-12">

      <table class="table table-striped">
        <caption>Doctors:</caption>
        <thead>
          <tr>
            <th>#</th>
            <th>Name</th>
            <th>Field</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
		
          <?php
if ($doctor_result->num_rows > 0) {
    while($row = $doctor_result->fetch_assoc()) {
        ?>
            <tr>
              <th scope="row">
                <?php echo $row['did'];?>
              </th>
              <td>
                <?php echo $row['name'];?>
              </td>
               <td>
                <?php echo $row['field'];?>
              </td>
              <td><a href="view_hospital.php?doctor_id=<?php echo $row['did']; ?>" class="btn btn-success pull-right">View</a></td>
            </tr>
            <?php
    }
}else{
    ?>
              <tr>
                <th scope="row"></th>
                <td>No doctors found</td>
                <td></td>
              </tr>
              <?php
}
?>
        </tbody>
      </table>
    </div>
  </div>
 
  <?php
  include ('comments.php');
  
include ('footer.php');
?>

the comments.php file

<?PHP
 # comments PHP code 
	
	date_default_timezone_set('Asia/Riyadh');
	
	function setComments (){
		if (isset($_POST['submitComments'])){
			include('setting.php');
				//$uid = $_POST['uid'];
				  $date = $_POST['date'];
				  $message = $_POST['message'];
				  
				  $sql = "INSERT INTO comments ( date, message) VALUE ( '$date', '$message')";
				  $result = mysqli_query($conn,$sql);
		}
	}
	function getComments (){
		if (isset($_POST['submitComments'])){
		include('setting.php');
		$sql = "SELECT * FROM comments";
		$result = mysqli_query($conn,$sql);
		while ($row = $result->fetch_assoc()){
			echo "<div class='comments-box'>";
			echo $row['date']."<br>";
			echo nl2br($row['message'])."<br><br>";
			echo "</div>";
		}
		}
		
	}
	
		echo "
		<form action='".setComments ()."' method='POST'>
  <input type='hidden' name='uid' value=''> 	
  <input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
  <textarea name='message' class='form-control' rows='3'></textarea>
  <br>
  <button type='submit' name='submitComments' class='btn btn-primary'>Comments</button>
  </form>
	<br><br>
	";

	getComments ();
 ?>
  

4
  • Side note, this is not a safe practice: $date = $_POST['date']; $message = $_POST['message']; $sql = "INSERT INTO comments ( date, message) VALUE ( '$date', '$message')"; You do not want to inject right into your SQL raw user data. Look into bind parameters. Commented Apr 4, 2017 at 16:41
  • I don't understand :( Commented Apr 4, 2017 at 16:50
  • 1
    @Archiveal-obaikan: He's talking about SQL injection, and your code is highly vulnerable to it. This is a good place to start on that: stackoverflow.com/questions/60174/… Basically, your code is executing whatever your users send you as though it too is code. That's a bad idea. Users can send you malicious code, and you'd execute it. Commented Apr 4, 2017 at 16:51
  • can I have your email to send all files to you , if you dn't mind Commented Apr 4, 2017 at 18:25

1 Answer 1

1

When you refresh in the browser, you send the last request again. That request was the POST of the form. So the user (browser) is telling the code to insert another comment.

Generally this is handled by redirecting after posting a form, rather than re-displaying the form again. Move all of your logic for (and only for) inserting the new content to its own PHP file (something like addComment.php) and have the form post to that file. Then in that file ensure that there is no actual output except perhaps to display an error message if something goes wrong?) and just a redirect back to the page:

header("Location: viewhospital.php");

This will instruct the browser in the response to make a new GET request for viewhospital.php. So if the user reloads the browser, all they're doing is repeating that GET request.

Sign up to request clarification or add additional context in comments.

7 Comments

it displays : Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\pqgs_desgin\viewhospital.php:86) in C:\xampp\htdocs\pqgs_desgin\comments.php on line 15
@Archiveal-obaikan: stackoverflow.com/questions/8028957/… As stated before, ensure that there is no other output besides the redirect.
what if I unset the function variable POST , do you think it works ??
@Archiveal-obaikan: What do you even mean by that?
such as unset($var) can I use it for $_POST
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.