doubo1711 2017-03-11 08:37
浏览 55
已采纳

使用Jquery .ajax()和PHP将数据插入数据库不起作用

So I am trying to insert data from a form using JQuery .ajax method. In the developer tools I see that the request is send to my process.php file, but I can't add the data to the database.

Javascript

$( document ).ready(function() {
    console.log( "ready!" );
    $("#submit").submit(function(e) {

        var url = "process.php"; // the script where you handle the form input.

        $.ajax({
               type: "POST",
               url: "process.php",
               data: $("#submit").serialize(), // serializes the form's elements.
               success: function(data){
                   alert("Data is send successifully!"); // show response from the php script.
               }
             });

        e.preventDefault(); // avoid to execute the actual submit of the form.
    });
});

Now I use my custom classes and methods.

This is the insert() method from my db.class.php

  public function insert($fName, $lName, $nickname){
    $query = "INSERT INTO users (first_name, last_name, nickname)
              VALUES ($fName, $lName, $nickname)";

    return $this->_conn->query($query);
  }

now I have user.class.php with add() method

  public function add($fName, $lName, $nickname){
    $db = new db();
    $db->insert($fName, $lName, $nickname);  
  }

Finally a process.php file. I'm sending my request there.

<?php
require_once 'classes/user.php';
require_once 'classes/db.php';

$user = new user();
$user->add($_POST['fName'], $_POST['lName'], $_POST['nickname']);

?>
  • 写回答

2条回答 默认 最新

  • dshun123456 2017-03-11 08:52
    关注

    Your values need to be interpreted as Strings in the SQL-Query, otherwise MySQL will think those are columns and will come up empty. Here is how you could do that:

    public function insert($fName, $lName, $nickname){
      $query = "INSERT INTO users (first_name, last_name, nickname)
              VALUES ('$fName', '$lName', '$nickname')";
    
      return $this->_conn->query($query);
    }
    

    It is generally recommended to use prepared statements to avoid SQL-Injection attacks though.

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口