PDO未插入DB

时间:2013-08-03 08:40:46

标签: php jquery pdo http-post

无法查看为什么没有插入数据...我有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>

1 个答案:

答案 0 :(得分:-2)

首先使用硬编码参数和使用exceptions的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 
}  

?>