PHP& MySQL没有将数据插入表(PDO)

时间:2016-02-10 16:42:19

标签: php mysql pdo

我无法将记录插入到我的数据库中,我检查了代码,所有变量和名称在PHP和数据库之间匹配。

没有错误消息,我收到的文字说明已创建预订,但没有记录输入数据库。

这是用于插入记录的php代码;

     <div class="containter">
      <?php
      if (isset($_POST['submit'])) {
         try {
             include ('include\PDO.php');
             $sql = "INSERT INTO customers(Customer_Name, Customer_Email, Customer_Contact) VALUES (:Customer_Name, :Customer_Email, :Customer_Contact)";

             //Named Parameters

             $stmt = $dbh->prepare($sql);

             if (!$stmt) {
                        echo "\nPDO::errorInfo():\n";
                        print_r($dbh->errorInfo());
                         }

             $Customer_Name = filter_input(INPUT_POST, 'Customer_Name');
             $stmt->bindValue(':Customer_Name', $Customer_Name, PDO::PARAM_STR);

             $Customer_Email = filter_input(INPUT_POST, 'Customer_Email');
             $stmt->bindValue(':Customer_Email', $Customer_Email, PDO::PARAM_STR);

             $Customer_Contact = filter_input(INPUT_POST, 'Customer_Contact');
             $stmt->bindValue(':Customer_Contact', $Customer_Contact, PDO::PARAM_STR);

             print $Customer_Contact;
             print $Customer_Name;
             print $Customer_Email;

             $stmt->execute();

             $dbh = null;


         } catch (PDOException $e) {
             //Error Messages
             print "We have had an error: " . $e->getMessage() . "<br/>";
             die();
         }         

     ?>

     <p> Booking Created.</p>

     <?php } else { ?>

     <form action ="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
         <label>Name:</label> <input type="text" name ="Cusomer_Name">
         <label>Email:</label> <input type="email" name ="Cusomer_Email">
         <label>Contact:</label> <input type="tel" name ="Cusomer_Contact">
         <input type="submit" name ="submit">
     </form>

     <?php } ?>
</div>
</body>
</html>

我已经检查了我能想到的一切,但我似乎无法将记录添加到数据库中。

关于我做错了什么的想法?

2 个答案:

答案 0 :(得分:5)

在html表单中,您有:

<label>Name:</label> <input type="text" name ="Cusomer_Name">

在PHP代码中,您过滤了Customer_Name:

$Customer_Name = filter_input(INPUT_POST, 'Customer_Name');

缺少&#39; t&#39;以html格式。

在html表单中放置Customer_Name而不是Cusomer_Name,并为Cusomer_Email和Cusomer_Contact执行相同的操作

答案 1 :(得分:0)

$stmt->execute();返回带有答案的布尔值。请尝试以下代码段来确定问题的确切位置:

$success = $stmt->execute();
if (!$success){
    print $stmt->errorInfo()[2]; //PDO driver error message
}