我喜欢用json,php和Ajax使用json_encode和Ajax Post更新我的数据库,但我不明白如何使用数组$ json_encode来为每个循环更新数据库。 ¿所以我如何用$ json_encode更新我的数据库?
这是我在单击保存订单按钮时在控制台中的响应:
{
"success": true,
"parent_id": [
"0,17,17,17,17,17,17,17,17,17,17,17,0,0,0"
],
"order_page": [
"3,4,5,6,7,8,9,10,11,12,13,14,0,1,2"
],
"id_page": [
"17,8,9,2,3,4,5,6,7,11,10,1,16,14,15"
]
}
这是我的帖子ajax php event saveorder.php
<?php
header('Content-type: text/javascript');
$json = array('success'=>false,
'parent_id' =>array($_POST['parent_id']),
'order_page' => array($_POST['order_page']),
'id_page'=>array($_POST['id_page'])
);
if(isset($_POST['parent_id'],$_POST['order_page'],$_POST['id_page'])){
$json = array('success'=>true,
'parent_id' =>array($_POST['parent_id']),
'order_page' => array($_POST['order_page']),
'id_page'=>array($_POST['id_page'])
);
echo json_encode($json);
$con = $this->connect();
$Ordersaved=json_decode($json);
foreach($Ordersaved as $key){
mysqli_query($con, "UPDATE pages SET parent_id='$parent_id' Order_Page=$order_page ID_Page=$id_page WHERE Section_ID=0 " );
}
}
elseif(is_null($_POST['parent_id'],$_POST['order_page'],$_POST['id_page'])){
echo "Las variables son nulas";
}
function connect(){
return mysqli_connect("localhost", "root","root","db");
}
?>
这是我的db:
CREATE TABLE `pages` (
`ID_Page` int(11) NOT NULL,
`TitlePage` varchar(255) NOT NULL,
`SectionPage` varchar(255) NOT NULL,
`CategoryPage` varchar(255) NOT NULL,
`NamePage` varchar(255) NOT NULL,
`BodyPage` varchar(9000) NOT NULL,
`DescriptionPage` varchar(255) NOT NULL,
`parent_id` int(11) unsigned NOT NULL DEFAULT '0',
`Section_ID` int(11) NOT NULL DEFAULT '0',
`Category_ID` int(11) NOT NULL DEFAULT '0',
`Order_Page` int(11) DEFAULT '0'
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT ;
答案 0 :(得分:1)
无需解释,我认为你可以发现差异:
$json = array('success'=>false,
'parent_id' => $_POST['parent_id'],
'order_page' => $_POST['order_page'],
'id_page'=>$_POST['id_page']
);
if(isset($_POST['parent_id'],$_POST['order_page'],$_POST['id_page'])){
$json = array('success'=>true,
'parent_id' => $_POST['parent_id'],
'order_page' => $_POST['order_page'],
'id_page'=> $_POST['id_page'])
);
echo json_encode($json);
$con = $this->connect();
// HERE
mysqli_query($con, "UPDATE pages SET parent_id=".$json['parent_id'].", Order_Page=".$json['order_page'].", ID_Page=".$json['id_page']." WHERE Section_ID=0 " )
// $Ordersaved=json_decode($json);
//foreach($Ordersaved as $key){
// mysqli_query($con, "UPDATE pages SET parent_id='$parent_id' Order_Page=$order_page ID_Page=$id_page WHERE Section_ID=0 " );
//}