drqvr26084 2019-04-22 06:47 采纳率: 100%
浏览 103
已采纳

使用JQuery AJAX和php将数据提取到mysql数据库

Im trying to insert data into my database with AJAX but dont working. I can verify that im connected to the database but when i click it doesnt insert the data. thanks

with a click function i take the 2 parameter that i wanna insert in my database.

$( "#q_answer1" ).click(function () {
      var q_no = $("#q_no").val(); 
      var main_no = $("#total_no").val();

      $.ajax({
         url: "server.php",
         type: "post",
         async: false,
         data: {
            "done": 1,
            "username": q_no,
            "comment": main_no

         }, 
         success: function(){
            $("#q_no").val('');
            $("#total_no").val('');
         }
      });
  });

And here is the php file, first connect to the ddbb and insert the 2 values with the mysql_query.

<?php
include("dbh.php");
if (isset($_POST['done'])) {
   $q_no = mysql_escape_string($_POST['username']);
   $total_no = mysql_escape_string($_POST['comment']);

   mysql_query("INSERT INTO variables(id, names) VALUES('{$q_no}', '{$total_no}')");
   exit();
}
?>

html is like this:

<div id="total_no">1</div>
<div id="q_answer1" class="btn left_b">yes</div>

  • 写回答

4条回答 默认 最新

  • duan246558 2019-04-22 09:04
    关注

    I think you should use PDO, to connect to the database instead of the old driver, which PHP no longer supports. with PDO you can use prepared statements to prevent sql injections

    PDO tutorial

    filter_var() Constants

    dbh.php

    $servername = "localhost";
    $username = "user";
    $password = "pass";
    $dbname = 'db';
    
    try {
    
      $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      }
      catch(PDOException $e)
      {
        exit($e->getMessage());
      }
    
    ?>
    

    serve.php

    <?php
    
    include("dbh.php");
    if (isset($_POST['done'])) {
    
       $q_no = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
       $total_no = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
    
    try {
    
      $stmt = $db->prepare("INSERT INTO variables(id, names) VALUES(?, ?)");
      $stmt->execute(array($q_no, $total_no));
    
      echo json_encode(["message" => "success"]); // sends success response to front-end 
    
    } catch (\Exception $e) {
      echo json_encode(["message" => $e->getMessage() ]); // sends error response to front-end
    }
    
    
    }
     ?>
    

    in your ajax check if the data was inserted or not.

    $("#q_answer1").click(function() {
      var q_no = $("#q_no").val();
      var main_no = $("#total_no").val();
    
      $.ajax({
        url: "file.php",
        type: "post",
        async: false,
        data: {
          "done": 1,
          "username": q_no,
          "comment": main_no
    
        },
        success: function(data) {
    
          const respose = JSON.parse(data);
    
          if (respose.message === 'success') { // data was inserted 
    
            $("#q_no").val('');
            $("#total_no").val('');
    
          }else {
            alert(respose.message); // some error has occured
          }
        }
      });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Qt安装后运行不了,这是我电脑的问题吗
  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法