通过jQuery发布记录并通过PHP保存在DB中

时间:2015-07-30 12:17:04

标签: javascript php jquery html mysql

我在MySQL DB中使用PHP保存记录时遇到了问题。 我想通过Post的jQuery方法发送用户信息并保存到数据库中 HTML:

<html>
    <body>
        <head>
            <script src="popcorn/js/jquery-1.10.2.js"></script>
            <script type="text/javascript">
                $(document).ready(function () {
                    $("#submit").click(function () {
                        var email = $("#email").val();
                        var name = $("#name").val();
                        $.post('/send.php', {
                            email: email,
                            name: name
                        }, function (data) {
                            console.log(data);
                        });
                    });
                });
            </script>
        </head>
        <input type="email" name="email" id="email"/>
        <input type="text" name="name" id="name"/>
        <input type="submit" id="submit" />
    </body>
</html>

并在/send.php中通过PHP获取信息
PHP:

    <?php
      include 'jdf.php';

      $servername = "localhost";
      $username = "popcorn";
      $password = "0201243aa";
      $dbname = "popcorn";

      $created = date("Y-m-d H:i:s",time());
      $name =  $_POST['name'];
      $email = $_POST['email'];

      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      // Check connection
      if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
      }

      $sql = "INSERT INTO `popcorn-app`(`id`, `email`, `name`, `created`) VALUES (NULL,$email,$name,$created)";

      if ($conn->query($sql) === TRUE) {
          echo "New record created successfully";
      } else {
          echo "Error: " . $sql . "<br>" . $conn->error;
      }

      $conn->close();
      ?> 

但我的问题在这里,当我把信息和POST与jQuery,控制台给我一个错误。

16:44:43.676 "Error: INSERT INTO `popcorn-app`(`id`, `email`, `name`, `created`) VALUES (NULL,goldast.xps@gmail.com,mohammad,2015-07-30 16:44:47)<br>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@gmail.com,mohammad,2015-07-30 16:44:47)' at line 1 "1 post.html:13:5

4 个答案:

答案 0 :(得分:0)

传递字符串值&#34; &#34 ;.
即。(NULL,'$email','$name','$created')

答案 1 :(得分:0)

用以下代码替换此行。这应该可以解决你的问题。

  $sql = "INSERT INTO `popcorn-app`(`id`, `email`, `name`, `created`) VALUES (NULL,'$email','$name',$created)";

这是因为您的表格中的电子邮件和名称应为char或varchar。

答案 2 :(得分:0)

$sql = "INSERT INTO `popcorn-app`(`email`, `name`, `created`) VALUES ('".$email.".,'".$name."','".$created."')";

如果id是自动递增,则无需添加查询。

答案 3 :(得分:0)

尝试使用:

$sql = "INSERT INTO `popcorn-app`(`email`, `name`, `created`) VALUES ('".$email."','".$name."','".$created."')";