【问题标题】:Can't insert FormData in mysql using Php and jquery ajax无法使用 Php 和 jquery ajax 在 mysql 中插入 FormData
【发布时间】:2018-06-06 02:31:59
【问题描述】:

我正在尝试使用 Jquery ajax 在 mysql 表中插入数据。我的jquery代码如下。

$("#join-form-submit").on("click", function(){
 if($("#join-fullname").val() && $("#join-username").val() && $("#join-email").val() && $("#join-phone").val() && $("#join-location").val()){

   var formData = new FormData();

   var fullname = $("#join-fullname").val();
   formData.append('fullname', fullname);

   var username = $("#join-username").val();
   formData.append('username', username);

   var email = $("#join-email").val();
   formData.append('email', email);

   var phone = $("#join-phone").val();
   formData.append('phone', phone);

   var location = $("#join-location").val();
   formData.append('location', location);

   $.ajax({
       url : 'new_sales.php',
       type : 'POST',
       data : formData,
       contentType : false,
       processData : false,
       success : function(data){
           alert("Success");
           console.log(fullname);
           console.log(username);
           console.log(email);
           console.log(phone);
           console.log(location);
       }
   });

 } else {
   $(".join-form-error").slideDown().delay(3000).slideUp();
 }
 });

这部分工作正常,单击按钮后我在 console.log 中获取输入数据,但数据未插入 mysql 服务器。

new_sales.php 处的代码如下

 <?php

  $fullname = $_POST["fullname"];

  $user_name = $_POST["username"];

  $email = $_POST["email"];

  $phone = $_POST["phone"];

  $location = $_POST["location"];

  $conn = new mysqli("localhost", "zzz", "xxxx", "wedoinst_main");

 $sql = "INSERT INTO new_sales (fullname, user_name, email, phone, location) VALUES ('$fullname', '$user_name', '$email', '$phone', '$location')";


 ?>

请指出我在这里做的错误。

谢谢

【问题讨论】:

  • 在这段代码中你没有执行 sql。我会使用准备好的语句来避免 SQL 注入攻击,而不是将变量放在查询中。

标签: php jquery mysql ajax mysqli


【解决方案1】:

您需要执行查询。

$conn->query($sql);

还需要使用prepared statements来防止sql注入

 $sql = "INSERT INTO new_sales (fullname, user_name, email, phone, location) VALUES (?,?,?,?,?)";

$result = $conn->prepare($sql); 
$result->bind_param('sssss',$fullname, 
$user_name,$email, $phone, $location); 
echo $result->execute() === true ?  'success' : 'query failed '. $conn->error;

【讨论】:

  • 我了解prepared statement的使用,但我错过了$conn-&gt;query($sql)部分。感谢您的帮助。
  • 很高兴。乐于助人
猜你喜欢
  • 2013-12-27
  • 2011-07-05
  • 1970-01-01
  • 2016-10-12
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 2016-12-12
  • 2020-10-24
相关资源
最近更新 更多