douaoj0994 2014-03-01 21:58
浏览 38
已采纳

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

This is my first time creating a php form and so I've been reading and copying a ton of tutorials, but none really seem to cover everything from start to finish so I'm piecemealing different people's decisions into one file and it isn't really working.

I think I understand what I've been learning so far, I just don't know enough about how to troubleshoot this php and find out where it's going wrong. Here's the 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>

The 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>

Here is the 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();
?>

Now I have rewritten this as I understood the tutorials and taken what the tutorials were saying and tried to apply it to my use case, so anything wrong with the above is my own fault and not the case that I'm following bad advice.

GOAL:

  1. Submit an html form for the fields
  2. Add them to the db
  3. Return the results of the submission to the page where <div class="return">
  4. Return the previous 10 results of prior submissions where <div class="previous"> (hence the i<11 part)
  • 写回答

2条回答 默认 最新

  • drqrdkfue521903877 2014-03-02 00:10
    关注

    First you must use name attribute in each your input tag. Eg.:

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

    The js code could be like this:

    <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>
    

    And this is for PHP script. The line with comment sign is your first script:

    <?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();
    ?>
    

    That's all. I have tried it before and everything is worked. Hope this can help you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路