我是PHP5中的新成員,我想使用AJAX和jQuery將數據插入到我的SQL中。我嘗試了太多的代碼,但沒有得到任何積極的迴應。如何使用PHP5將數據插入到MySQL中AJAX
任何人都可以幫我解決我的問題嗎?
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的& 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>
將alert(name)更改爲alert(responseText);這會給出什麼結果? – Alex
將腳本放在腳本的某處以便檢查腳本是否正在運行,並且在firefox中還有螢火蟲,以便您可以檢查控制檯,一個D也「插入後('後')值('」。$ name。「');」 –