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

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀