这就是我的JSON的样子:
$return='{"sub":{"2":""},"postcode":"56000","slider1":"100","action":"test"}';
$data = json_decode($return, true);
这就是我获得价值的方式,
$postcode=$data['postcode'];
$budget = $data['slider1'];
$subject =$data['sub'];
var_dump($key =array_keys($data['sub']));// this prints 0=>2
foreach($key as $key1=>$key2)
{
$key1;//prints 0
$key2;//prints 2
}
$key2;//prints 2
我正在插入这样的数据:
try {
//$pdo = new PDO('mysql:host=localhost;dbname=users', $username, $password);
//$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$stmt = $pdo->prepare('INSERT INTO test (postcode,budget,subject) VALUES(:postcode,:budget,:subject)');
$stmt->execute(array(
':postcode' => $postcode,
':budget'=> $budget,
':subject'=> $key2
));
# Affected Rows?
$stmt->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
上述查询将数据两次插入数据库。我检查了chrome dev工具中的网络选项卡,它显示了此文件的请求被发送两次。
有没有办法一次只插入一次数据?我的意思是有没有办法限制查询?
已编辑
AJAX
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize();
$.ajax({
type: "POST",
dataType: "json",
url: "writedb.php", //Relative or absolute path to writedb.php file
data: data,
success: function(data) {
//.....
}