PHP Chatbox:无法发送到MySQL数据库

PHP Chatbox:无法发送到MySQL数据库

问题描述:

Code :

        $user = $_POST["user"];
        $message = $_POST["message"];
        $message = htmlspecialchars($message);

        $db=mysqli_connect("host","username","pwd","db");

        if (mysqli_connect_errno()){
            echo "Failed to connect to MySQL: " . mysql_connect_error();
        }

        #Connected   

        if(isset($message) == true && $message != "" && $message != " "){
            if(isset($user) == false){
                $user = "visitor";
            }

            $sql="
            INSERT INTO ChatBox (DateTime, User, Content)
            VALUES
            (now(),'$_POST[User]','$_POST[Content]')
            ";

            if (!mysqli_query($db,$sql))
            {
            die('Error: ' . mysqli_error($db));
            }
            }

            mysqli_close($db);

This is my code in a chatbox.

However, I use the line if(isset($message) == true && $message != "" && $message != " "){ to find out whether $_POST['message'] is null or not.

Finally, I cannot insert anything in my chat box.

This is my chatbox link : http://jamie-is-cool.comeze.com/chat.php

The problem is that : After clicking Send! nothing happened. It just reload and didn't send.

What should I do?

A complete list of code is available here.

Insert code block will on fire if the statement if( isset( message) ... returns a true.

But in your HTML form, there is no such element with name message but a user and content.

<form action="chat.php" style="margin:0px;padding:1px;" method="POST">
  User: <input type="text" style="width:15%;" name="User" /> | 
  <input type="text" style="width:65%;" name="Content" />
  <input type="submit" value="Send!" style="width:10%;" />
</form>

Add an input type element named message to the form with some value and then submit to get succeed.

<form action="chat.php" style="margin:0px;padding:1px;" method="POST">
  User: <input type="text" style="width:15%;" name="User" /> | 
  <input type="text" style="width:65%;" name="Content" />
  <input type="text" style="width:65%;" name="message" />
  <input type="submit" value="Send!" style="width:10%;" />
</form>

For better display, adjust the form table display width accordingly.