如何使用PHP5 AJAX将数据插入MySQL

时间:2015-11-06 20:25:24

标签: jquery mysql ajax php-5.3

我是PHP5的新手,我想使用AJAX和jQuery将数据插入到我的SQL中。我尝试过太多代码但没有得到任何积极的回应。

任何人都可以帮我解决我的问题吗?

PHP代码:

<?php
class Crud{

private $host="localhost";
private $username="root";
private $password="";
private $db_name="comment-system";
public $mysqli;

public $data;

public function __construct(){

    $this->mysqli = new mysqli($this->host, $this->username, $this->password, $this->db_name);

    if(mysqli_connect_errno()) {

        echo "Error: Could not connect to database.";

    exit;

    }
    /*else{
        echo"Your Database successfully connected"; 
    }*/

}

public function __destruct(){
    $this->mysqli->close(); 
}

public function read(){

    $query="SELECT * FROM test";

    $result= $this->mysqli->query($query);

    $num_result=$result->num_rows;


    if($num_result>0){
        while($rows=$result->fetch_assoc()){

            $this->data[]=$rows;

            //print_r($rows);

        }

        return $this->data;
    }
}

public function insert($name){

 $query="INSERT INTO post SET post='$name'";

    $result= $this->mysqli->query($query) or   die(mysqli_connect_errno()."Data cannot inserted");

    if($result){
        header('location:index.php');   
    }
}
}

  //$obj=new Crud("localhost","root","","oop_crud");

 //$obj->read();
?>

HTML代码

<script src="jquery-1.8.3.js"></script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="" content="">
</head>
<body>
<div id="maindiv">
<h3>post Detail:</h3>
<h3><textarea id="txtarea" >my name is khan</textarea></h3>
<h3><button id="save" title="post">post</button></h3>

</div>
</body>

jQuery&amp; AJAX

<script>
$("#save").click(function(){
    var name =$("#txtarea").val();
     $.ajax({
             type: "POST",
             contentType: "application/json; charset=utf-8",
                   url: "Crud/insert",
            data: "{'name':'" + name + "'}",
              async: false,
              success: function (responseText) {
                alert(name);
           }
          });
 });
 </script>

</html>

2 个答案:

答案 0 :(得分:0)

我相信您的数据库操作PHP代码工作正常。这是HTML和AJAX代码,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title></title>
    <meta name="" content="">
</head>
<body>
    <div id="maindiv">
        <h3>post Detail:</h3>
        <h3><textarea id="txtarea" >my name is khan</textarea></h3>
        <h3><button id="save" title="post">post</button></h3>

    </div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $(document).on('click','#save',function(){
            var name = $("#txtarea").val();
            var param = {name: name};

            $.ajax({
                type: 'POST',
                url: 'ajax_page.php',
                cache: 'false',
                data: param,

                beforeSend: function(){
                    // function to perform before sending data
                },

                success: function(data){
                    alert(data);
                },

                error: function(){
                    // function to perform if unexpected error occurs 
                }
            });
        });
    });
    </script>
</body>
</html>

ajax代码将数据/参数发送到 ajax_page.php 页面,您可以使用 $ _ POST ['name'] 来捕获参数并执行数据库操作。

希望这会对你有所帮助。

答案 1 :(得分:-1)

您的问题来自INSERT SQL的语法。

请通过$ name = $ _POST [&#34; name&#34;];

获取名称的值

它应该有效:

 $query="INSERT INTO post (`post`) VALUES ('$name')";

请查看有关SQL插入语法的更多详细信息: INSERT SQL SYNTAX