-1

无法看到为什么没有插入数据...我有 jQuery、HTML 和 PHP 代码,它们都将在下面发布。尝试调试无济于事。谢谢。

PHP代码:

<?php
include_once('db.php');
session_start();

    $message = $_POST['message'];

        if($message < 100 && $message > 2) {

            $insertMessage = $db->prepare("INSERT INTO `chats`(`time`, `message`, `username`) VALUES(:time, :message, :username)");

                $insertMessage->execute(array(

                        ':time'     => date("g:i a"),
                        ':message'  => $message,
                        ':username' => $_SESSION['username']

                    ));


        }
?>

jQuery代码:

$("#chatBtn").click( function() {
 $.post( $(".chatForm").attr("action"), 
         $(".chatForm :input").serializeArray(), 
         function(info){ $("#chatResult").html(info); 
      $('#message').val('');

   });
});

$(".chatForm").submit( function() {
  return false; 
  $('#message').val('');
});

HTML 代码:

<form action="./php/send_chat.php" method="POST" class="chatForm">
<p class="field">
<input type="text" id="message" name="message" style="width: 275px;">
<span><button type="submit" id="chatBtn">Send</button>
</p>
</form>
4

1 回答 1

-2

首先使用硬编码参数简化插入,并在带有异常的 try/catch 中 PDO::ERRMODE_EXCEPTION 触发异常,允许您优雅地处理错误。一旦这产生了所需的结果,在每次修改后逐步修改您的代码检查。这是基本调试。

<?php
include_once("db.php");
$message ="Test Message";
$username = "username";
// connect to the database  
try {  
    $db = new PDO("mysql:host=$host;dbname=$database", $username, $password);  
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
    //
    $insertMessage = $db->prepare("INSERT INTO `chats`(`time`, `message`, `username`) VALUES(:time, :message, :username)");
    $insertMessage->execute(array(
        ':time'     => date("g:i a"),
        ':message'  => $message,
        ':username' => $username
        ));

  }   
catch(PDOException $e) {  
    echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing 
}  

?>
于 2013-08-03T10:41:53.297 回答