2016-02-05 209 views
1

我有一個網站,我需要把一個聊天框,但是當有人寫的用戶必須刷新整個頁面閱讀文本,但我需要做到這一點自動更新數據請幫幫我。如何更新數據從MySQL數據庫刷新頁面

現在,這是代碼:

<? 
session_start(); 
include("includes/config.php"); 
if($_GET['with']){ 
    if($_SESSION['login']){ 
     if($_SESSION['login'] == $_GET['with']){ 
      header("Location: index.php"); 
     }else{ 
     $id = $_SESSION['login']; 
     $with = intval($_GET['with']); 
      if($_POST['submit']){ 
       $text = $_POST['text']; 
       if(empty($text)){ 

       }else{ 
        $query = mysqli_query($connect,"INSERT INTO chat(`from`,`to`,`topic`) VALUES('$id','$with','$text')"); 
       } 
      } 
     ?> 
      <form method="post" action="chat.php?with=<?=$with?>"> 
       <textarea name="text" placeholder="Write Here..." style="text-align:right;resize:none;width:100%;height:200px;font-size:24"> 
       </textarea> 
       <br/> 
       <input type="submit" name="submit" value="Send"/> 
      </form> 
      <div id="chat"> 
     <? 
     $query = mysqli_query($connect,"SELECT * FROM users WHERE id='$id'"); 
     $f = mysqli_fetch_array($query); 
     $query = mysqli_query($connect,"SELECT * FROM users WHERE id='$with'"); 
     $ff = mysqli_fetch_array($query); 
     $query = mysqli_query($connect,"SELECT * FROM chat order by id desc"); 
     while($fetch = mysqli_fetch_array($query)){ 
      if($fetch['from'] == $with && $fetch['to'] == $id or $fetch['from'] == $id && $fetch['to'] == $with){ 
       if($fetch['from'] == $f['id']){ 
        echo "<div style='word-wrap: break-word;'>".$f['fname']."&nbsp;".$f['lname'].":<br/>".$fetch['topic']."</div>"; 
       } 
       if($fetch['from'] == $ff['id']){ 
        echo "<div style='max-width:200px;word-wrap: break-word;'>".$ff['fname']."&nbsp;".$ff['lname'].":<br/>".$fetch['topic']."</div>"; 
       } 
      } 
     }?> 
     </div> 
     <?} 
    }else{ 
     header("Location: index.php"); 
    } 
}else{ 
    header("Location: index.php"); 
} 

>

+0

Ajax,棘輪(Websockets)!使用它們...他們將幫助 – Tushar

+0

您好,我可以編寫一個可以刷新div的代碼嗎? –

+0

是的,嘗試搜索一下;-) http://stackoverflow.com/questions/17886578/refresh-part-of-page-div –

回答

0

Ajax會幫助你。但是,在相同的代碼中混合使用html和php的方式是一種糟糕的做法;像這樣,許多人很難幫助你用ajax來調整你的代碼。