Javascript 使用 Ajax 和 PHP 插入数据库(mysql)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38794652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:51:46  来源:igfitidea点击:

Insert into database (mysql) using Ajax and PHP

javascriptphphtmlmysqlajax

提问by Colin

I am trying to insert data from a form into a mysql database. The place I think the issue is, is where Im using the button in the HTML hence why I copied all of it over. Any help would be appreciated!

我正在尝试将表单中的数据插入到 mysql 数据库中。我认为问题所在的地方是我在 HTML 中使用按钮的地方,因此我将其全部复制。任何帮助,将不胜感激!

When I hit the submit button, the page flashes and nothing is inserted into the DB. It should display a green box saying the record has been submitted on the html page.

当我点击提交按钮时,页面闪烁并且没有任何内容插入到数据库中。它应该显示一个绿色框,表示该记录已在 html 页面上提交。

Because some people are more worried Im building an authentication system then whats wrong. This is NOTan authentication system, its just an example of how to insert into a mysql db.

因为有些人更担心我正在构建一个身份验证系统,那有什么问题。这不是身份验证系统,它只是如何插入 mysql 数据库的示例。

Index.html

索引.html

<!DOCTYPE html>
<html lang="en">
<head>
 <title>Bootstrap Example with Ajax</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
 <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 <script src="js/insert.js"></script>
 
 <style>
  .custom{
   margin-left:200px;
  }
 </style>
</head>
<body>

<div class="container">
 <h2 class="text-center">Insert Data Using Ajax</h2>
 
 <br/>
 <p id="alert" style="display:none;" class="alert alert-success text-center"><i class="glyphicon glyphicon-ok"></i><span> id="show"</span></p>
 <br/>
 <hr/>
 <form class="form-horizontal" role="form" method="POST">
  <div class="form-group">
   <label class="col-sm-2 control-label">Name</label>
    <div class="col-sm-10">
     <input class="form-control" id="name" type="text" placeholder="Enter you name">
    </div>
   </div>
   <div class="form-group">
    <label for="email" class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
     <input class="form-control" id="email" type="text" placeholder="Your Email...">
    </div>
   </div>
   <fieldset >
    <div class="form-group">
     <label for="password" class="col-sm-2 control-label">Password</label>
     <div class="col-sm-10">
     <input class="form-control" id="password" type="text" placeholder="Your Password...">
    </div>
   </div>
   <div class="form-group">
    <label for="gender" class="col-sm-2 control-label">Gender</label>
    <div class="col-sm-10">
    <select id="gender" class="form-control">
     <option value="Male">Male</option>
     <option value="Female">Female</option>
    </select>
    </div>
   </div>
  <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-default">Submit</button>
      </div>
    </div>
  </form>
</div>
</body>
</html>
   
   
    

insert.php

插入.php

<?php
 //Create connection
 $connection = mysqli_connect('localhost','username','passwd','dbName');
 
 if($_REQUEST['name']){
 $name = $_REQUEST['name'];
 $email = $_REQUEST['email'];
 $password= $_REQUEST['password'];
 $gender = $_REQUEST['gender'];
 
 $q = "INSERT INTO user VALUES ('','$name', '$email', '$password', '$gender')";
 
 $query = mysqli_query($connection,$q);
 if($query){
  echo ' Data Inserted Successfully'
        mysql_close($connection);
  }
 }
?>

js/insert.js

js/insert.js

$(document).ready(function(e) {
 $('#submit').click(function(){
  var name = $('#name').val();
  var email = $('#email').val();
  var password = $('#password').val();
  var gender = $('#gender').val();
  
  $ajax({
   type:'POST',
   data:{name:name,email:email,password:password,gender:gender},
   url:"insert.php", //php page URL where we post this data to save in databse
   success: function(result){
   
    $('#alert').show();
    
    $('#show').html(result);
      
    
   }
  })
 });
});

回答by Luna

Anyway, this particular code works out to allowing insertion into database, though there are still some problem somewhere which I cannot find out.

无论如何,这个特定的代码允许插入到数据库中,尽管在某处仍然存在一些我无法发现的问题。

index.html

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example with Ajax</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script>
      $(function () {
        $('button').click(function () {
          var name2 = $('#name').val();
          var email2 = $('#email').val();
          var password2 = $('#password').val();
          var gender2 = $('#gender').val();
          console.log('starting ajax');
          $.ajax({
            url: "./insert.php",
            type: "post",
            data: { name: name2, email: email2, password: password2, gender: gender2 },
            success: function (data) {
              var dataParsed = JSON.parse(data);
              console.log(dataParsed);
            }
          });

        });
      });

    </script>

    <style>
      .custom{
         margin-left:200px;
      }
    </style>
  </head>
  <body>

    <div class="container">
      <h2 class="text-center">Insert Data Using Ajax</h2>

      <form class="form-horizontal" >
        <div class="form-group">
          <label class="col-sm-2 control-label">Name</label>
          <div class="col-sm-10">
            <input class="form-control" name="name" id="name" type="text" placeholder="Enter you name">
          </div>
        </div>
        <div class="form-group">
          <label for="email" class="col-sm-2 control-label">Email</label>
          <div class="col-sm-10">
            <input class="form-control" name="email" id="email" type="text" placeholder="Your Email...">
          </div>
        </div>
          <div class="form-group">
            <label for="password" class="col-sm-2 control-label">Password</label>
            <div class="col-sm-10">
              <input class="form-control" name="password" id="password" type="text" placeholder="Your Password...">
            </div>
          </div>
          <div class="form-group">
            <label for="gender" class="col-sm-2 control-label">Gender</label>
            <div class="col-sm-10">
              <select id="gender" class="form-control">
                <option value="Male">Male</option>
                <option value="Female">Female</option>
              </select>
            </div>
          </div>
          <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
              <button type="submit" class="btn btn-default">Submit</button>
            </div>
          </div>
      </form>
    </div>
  </body>
</html>

insert.php

插入.php

<?php

    //Create connection
  $connection = mysqli_connect('localhost', 'root', '', 'dbase');
    if($_POST['name']){
      $name = $_POST['name'];
      $email = $_POST['email'];
      $password= $_POST['password'];
      $gender = $_POST['gender'];

      $q = "INSERT INTO user (name, email, password, gender) VALUES ('$name', '$email', '$password', '$gender')";

      $query = mysqli_query($connection, $q);

      if($query){
          echo json_encode("Data Inserted Successfully");
          }
      else {
          echo json_encode('problem');
          }
      }

?>

回答by Jonathan Harvey

First, the jQuery event handler that you're attaching to an element with the ID "submit" is never going to fire, since it won't match any elements in your html. Change your html to something like this:

首先,您附加到 ID 为“submit”的元素的 jQuery 事件处理程序永远不会触发,因为它不会匹配您的 html 中的任何元素。将您的 html 更改为如下所示:

<button type="submit" name="submit" id="submit"> Submit! </button>

<button type="submit" name="submit" id="submit"> Submit! </button>

Then, you need to alter your SQL syntax a bit. Your query is:

然后,您需要稍微更改 SQL 语法。您的查询是:

$q = "INSERT INTO user VALUES ('','$name', '$email', '$password', '$gender')";

$q = "INSERT INTO user VALUES ('','$name', '$email', '$password', '$gender')";

where you tell mysql to insert those values into the "user" table but you don't tell it which columns to insert into. You need something like this:

你告诉 mysql 将这些值插入到“用户”表中,但你没有告诉它要插入哪些列。你需要这样的东西:

$q = "INSERT INTO user (name, email, password) VALUES ('$name', '$email', '$password', '$gender')";

$q = "INSERT INTO user (name, email, password) VALUES ('$name', '$email', '$password', '$gender')";

I assume the blank string in your VALUES is supposed to reserve a spot for the ID of the insertion...if you have auto-incrementing turned on in your DB table you don't have to include the blank string. This is just a start to fix your issues, but if you include more details about what errors you're recieving we may be able to help more.

我假设您的 VALUES 中的空白字符串应该为插入的 ID 保留一个位置……如果您在数据库表中打开了自动递增,则不必包含空白字符串。这只是解决您的问题的一个开始,但如果您提供有关您收到的错误的更多详细信息,我们可能会提供更多帮助。