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 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案