doubi8383
doubi8383
2014-09-09 16:58

使用ajax将数据插入mysql

  • php
  • mysql
  • ajax
  • jquery
  • sql

I'm trying to insert data to mysql, tried everything but nothing worked

here is my code :

Javascript:

<script type="text/javascript">
  $(document).ready(function(){
    $("#rating-btn").click( function(){
      var teaching=$("#teaching").val;
      var marking=$("#marks").val;
      var helpfulness=$("#helpfulness").val;
      var difficulty=$("#difficulty").val;
      var grade=$("#grade").val;
      var com=$("#com").val;

  $.ajax({
    type: "POST",
    url:"db/ajax.php",
    data:"teaching=" + teaching +"&marking="+ marking +"&helpfulness="+ helpfulness
    +"&difficulty="+difficulty+"&grade="+grade+"&com="+com,
    dataType: "dataString",
    cache: "true",
    success: function(msg,string,jqXHR){
      $("#results").html(msg+string+jqXHR);
    }
    });

  });

});

ajax.php

<?php 

 error_reporting(0);
 require 'db/connect.php';

    $teaching = $_POST['teaching'];
    $teaching = mysql_real_escape_string($teaching);

    $marking = $_POST['marking'];
    $marking  = mysql_real_escape_string($marking);

    $helpfulness = $_POST['helpfulness'];
    $helpfulness  = mysql_real_escape_string($helpfulness);

    $difficulty = $_POST['difficulty'];
    $difficulty = mysql_real_escape_string($difficulty);

    $grade = $_POST['grade'];
    $grade = mysql_real_escape_string($grade);

    $com= $_POST['com'];

    $sql = "INSERT INTO ratings VALUES ( '', '{$teaching}', '{$marking}' ,'{$helpfulness}', '{$difficulty}' ,'{$grade}' , '2' , '{$com}')";

   mysqli_query($sql);

?>

connect.php

<?php
$db= new mysqli('localhost','root','','instructors');

if($db->connect_errno){
    die("we are having some problems");
}

?>

I tried to the sql code and it worked in the phpmyadmin page.

So what is missing that is preventing the data from going into the database?

UPDATE: when i try to echo all the variables and thier values apears normally i also tried to do this :

$sql = "INSERT INTO `ratings` VALUES ( '', '3.5', '2.5' ,'4.5', '2.5' ,'1' , '2' , 'hello how are you')";

it does not insert this values to the database

but when i put the same sql code in the phpmyadmin its adds a row perfectly

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答