javascript - 使用 php 提交 html 并使用 Ajax 和 jQuery 保存到 MySQL Db?

标签 javascript php jquery mysql ajax

这是我第一次创建 php 表单,所以我一直在阅读和复制大量教程,但似乎没有一个真正涵盖从头到尾的所有内容,所以我将不同人的决定零碎地放在一个文件中,然后它并没有真正起作用。

认为我了解我到目前为止所学的内容,我只是不太了解如何解决此 php 问题并找出问题所在。这是 HTML:

<section class="content">
  <form method="POST" action="" enctype="multipart/form-data" name="form">
    <p>Please remember, these results are saved into the database and will be shown to other users. So please do not include any identifying or personal information.</p>
    <label>
      <input type="text" id="object" placeholder="Name an object" required="required" />
      <i class="fa fa-wrench"></i>
    </label>
    <label>
      <input type="text" id="location" placeholder="Name a location" required="required" />
      <i class="fa fa-map-marker"></i>
    </label>
    <label>
      <input type="text" id="person" placeholder="Name a person" required="required" />
      <i class="fa fa-user"></i>
    </label>
    <button type="submit">Submit</button>
  </form>
</section>
<section class="result">
  <div class="return"><?php echo $result; ?></div>
  <h2>See how other people have responded.</h2>
  <div class="previous"></div>
</section>

js:

<script type="text/javascript">
  $(function(){
    $("button").click(function(e){
      e.preventDefault();
      $.post("phptest.php", {$("form").serialize()}, function(res){
        $(".return").html(res);
        $(".content").hide();
        $(".result").show();
      });
    });
  });
</script>

这是 php:

<?php
  $mysqli = new mysqli('mysite.com', 'myuser', 'mypass', 'mydb');
  if($mysqli->errno) {
    printf("Connection To Database Failed:<br/> %s", $mysqli->error());
    die();
  };
  $query = "INSERT INTO test_table (person, object, location) VALUES ('{$person}', '{$object}', '{$location}')";
  $stmt = $mysqli->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param('sss', $person, $object, $location);
  $person = $_POST['person'];
  $object = $_POST['object'];
  $location = $_POST['location'];
  $results = $mysqli->query($query);
  $stmt->execute();
  $stmt->close();
  $mysqli->close();
?>
<?php
  $mysqli = new mysqli('mysite.com', 'myuser', 'mypass', 'mydb');
  if($mysqli->errno) {
    printf("Connection To Database Failed:<br/> %s", $mysqli->error());
    die();
  };
  $query = "SELECT person, object, location FROM test_table WHERE person = ?";
  $stmt = $mysqli->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param('sss', $person, $object, $location);
  $stmt->execute();
  $result = $stmt->get_result();
  while($row = $result->fetch_assoc()) {
    printf('<strong>%s</strong> is a person. <strong>%s</strong> is an object. <strong>%s</strong> is a location.', $row['person'], $row['object'], $row['location']);
  $stmt->close();
  $mysqli->close();
?>

现在我已经重写了这个,因为我理解了教程并采用了教程所说的内容并尝试将其应用到我的用例中,所以上面的任何错误都是我自己的错而不是我跟随错误的情况建议。

目标:

  1. 提交字段的 html 表单
  2. 将它们添加到数据库
  3. 将提交的结果返回到<div class="return">所在的页面
  4. 返回先前提交的前 10 个结果,其中 <div class="previous"> (因此是 i<11 部分)

最佳答案

首先,您必须在每个输入标签中使用 name 属性。例如:

<input type="text" id="location" name="location" placeholder="Name a location" required="required" />

js代码可以是这样的:

<script type="text/javascript">
  $(function(){
    $("button").click(function(e){
      e.preventDefault();
      $.post("phptest.php", $("form").serialize())
      .done(function(res) {
        $(".return").html(res);
        $(".content").hide();
        $(".result").show();
      });
    });
  });
</script>

这是针对 PHP 脚本的。带有注释符号的行是您的第一个脚本:

<?php
  $mysqli = new mysqli('mysite.com', 'myuser', 'mypass', 'mydb');
  if($mysqli->errno) {
    printf("Connection To Database Failed:<br/> %s", $mysqli->error());
    die();
  };
  //$query = "INSERT INTO test_table (person, object, location) VALUES ('{$person}', '{$object}', '{$location}')";
  $query = "INSERT INTO test_table (person, object, location) VALUES (?, ?, ?)";
  $stmt = $mysqli->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param('sss', $person, $object, $location);
  $person = $_POST['person'];
  $object = $_POST['object'];
  $location = $_POST['location'];
  $results = $mysqli->query($query);
  $stmt->execute();
  $stmt->close();
/* No need a new mysqli object, so i block some lines from your script
  $mysqli->close();
?>
<?php
  $mysqli = new mysqli('mysite.com', 'myuser', 'mypass', 'mydb');
  if($mysqli->errno) {
    printf("Connection To Database Failed:<br/> %s", $mysqli->error());
    die();
  };
*/
  $query = "SELECT person, object, location FROM test_table WHERE person = ?";
  $stmt = $mysqli->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param('s', $person); // The query just need one parameter
  $stmt->execute();
  $result = $stmt->get_result();
  while($row = $result->fetch_assoc()) {
    printf('<strong>%s</strong> is a person. <strong>%s</strong> is an object. <strong>%s</strong> is a location.', $row['person'], $row['object'], $row['location']);
  } // Don't forget to close a statement
  $stmt->close();
  $mysqli->close();
?>

就是这样。我以前试过,一切正常。希望对您有所帮助。

关于javascript - 使用 php 提交 html 并使用 Ajax 和 jQuery 保存到 MySQL Db?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120913/

相关文章:

php - 搜索 mysql 数据库并从 php 和 html 中的结果创建链接

php - 关于 CActiveDataProvider 与缓存数据库查询的奇怪行为

javascript - Uploadify 中有多种文件类型

javascript - 如何防止固定标题下的内容消失?

javascript - 使用 jquery 定义如何在基于数据表插件的网格中添加自定义链接按钮

javascript - 如何在我的文本冒险中的 If/Else 语句中打印正确的随机数组值?

javascript - Vue2 中的条件 Prop

javascript - 如何在不执行函数的情况下判断函数是否返回 Promise?

javascript - Angular JS,异步回调中的范围更新

php - MySqli:是否可以创建数据库?