我想实现一个功能,通过ajax发送名称和年龄。然后PHP将它们收集起来并存储到数据库中。我认为我的操作是正确的,但数据没有保存在数据库中。有人能帮我解决吗?
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function(){
$.ajax({
url: 'addData.php',
type: 'POST',
dataType: "json",
data: {
name: $('#name').val(),
age: $('#age').val(),
}
})
});
});
</script>
</head>
<body>
<input id="name" type="text" />
<input id="age" type="text" />
<button>Click</button>
</body>
</html>
PHP
<?php
//Parameters for connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test1";
//Reading json
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$name = $data_back->{"name"};
$age = $data_back->{"age"};
// Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Creating Query
$sql = "INSERT INTO table1 (name, age) VALUES ($name, $age)";
//Running Query
$conn->query($sql);
//Closing Connection
$conn->close();
?>
错误
...('$name', '$age')...
。 - Milan