为什么我的SQL在刷新页面时插入相同的数据?

时间:2017-06-10 23:17:28

标签: php sql

我是php编码的新手。我正在创建一个评论部分,但是当我每次在我的数据库中插入相同的评论时都提交评论。 这是我的PHP代码。

     <?php 
     function setComments( $mysqli ){
     if (isset($_POST['commentSubmit'])) {
       $uid= $_POST['uid'];
       $date= $_POST['date'];
       $message= $_POST['message'];

      $sql="INSERT INTO comments(uid,date,message) VALUES('$uid','$date','$message')";

    $result = $mysqli-> query($sql);
  }
}
function getComments( $mysqli ){
  $sql = "SELECT * FROM comments ORDER BY date DESC ";
  $result = $mysqli->query($sql);
     while ( $row = $result->fetch_assoc() ) {
        echo "<div class='comment-box' ><p>";
        echo $row['uid']."<br><br>";
        echo $row['date']."<br><br>";
        echo nl2br($row['message']);
        echo "<p></div>";
  }
}

这是输出和提交的代码

<?php

 echo "
   <div align='center'>
      <form method='POST' action='".setComments( $mysqli)."'>
        <input type='hidden' name='uid' value='Anwer'>
        <input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
        <textarea name='message'></textarea>
         <br>
        <button type='submit' name='commentSubmit' > Comment</button>
    </form>
    </div>"
    ;
  getComments($mysqli);

  ?>

1 个答案:

答案 0 :(得分:1)

这是问题所在。您正在运行时调用save函数而没有条件。作为一个例子;

<?php 
function setComments( $mysqli, $postArr ){
   $uid=  $postArr['uid'];
   $date= $postArr['date'];
   $message= $postArr['message'];
   $sql="INSERT INTO comments(uid,date,message) 
            VALUES('$uid','$date','$message')";
   $result = $mysqli-> query($sql);
}

// I'm calling save function only for submit event

if (!empty($_POST['commentSubmit'])) {
   setComments( $mysqli, $_POST);
}

 // For your HTML code;

echo "<div align='center'>
        <form method='POST' action=''>
          <input type='hidden' name='uid' value='Anwer'>
          <input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
          <textarea name='message'></textarea>
          <br>
          <button type='submit' name='commentSubmit'> Comment</button>
        </form>
    </div>";

getComments($mysqli);
?>