将JSON解码为类然后插入MySQL查询

时间:2016-10-20 17:14:13

标签: php mysql json

我有一个php函数,它创建一个JSON数组,然后发布到我的Web服务。该功能工作正常,但Web服务给了我一些问题。

我使用json_decode来解码传入的字符串,并将值分配给类。这工作正常。我正在使用以下内容进行解码,然后分配给我的班级

$obj = json_decode($json, true);
$classObj = new AppointmentList();
foreach ($obj  as $key => $value)
    $classObj->{$key} = $value;

var_dump($json);
var_dump($obj);
var_dump($classObj);

转储给了我这个

array(1) { ["AppointmentList"]=> array(10) { ["id"]=> string(0) "" ["MeetingId"]=> NULL ["MeetingName"]=> string(7) "derwent" ["DateTimeFrom"]=> string(13) "20th Oct 2016" ["Length"]=> string(0) "" ["Room"]=> string(4) "gere" ["Venue"]=> string(4) "gere" ["DateCreated"]=> string(10) "2016-10-20" ["DateDue"]=> string(10) "2016-10-20" ["UserId"]=> string(9) "JohnsonPa" } }

object(AppointmentList)#1 (11) { ["id"]=> string(0) "" ["MeetingId"]=> string(0) "" ["MeetingName"]=> string(0) "" ["DateTimeFrom"]=> string(0) "" ["Length"]=> string(0) "" ["Room"]=> string(0) "" ["Venue"]=> string(0) "" ["DateCreated"]=> string(0) "" ["DateDue"]=> string(0) "" ["UserId"]=> string(0) ""

["AppointmentList"]=> array(10) { ["id"]=> string(0) "" ["MeetingId"]=> NULL ["MeetingName"]=> string(7) "derwent" ["DateTimeFrom"]=> string(13) "20th Oct 2016" ["Length"]=> string(0) "" ["Room"]=> string(4) "gere" ["Venue"]=> string(4) "gere" ["DateCreated"]=> string(10) "2016-10-20" ["DateDue"]=> string(10) "2016-10-20" ["UserId"]=> string(9) "JohnsonPa" } }

填充约会列表。

我的问题是将这些数据输出到SQL查询中。我已经尝试了大量不同的方法来获取数据($ classObj-> AppointmentList-> MeetingName,$ classObj。['MeetingName']等等)它或者给我一个关于使用数组的错误或者什么都没有。

如何将此数据输出到SQL查询中?我当前的(不正确)看起来像这样

$query = "REPLACE INTO AppointmentList (id, MeetingId, MeetingName, DateTimeFrom, Length, Room, Venue, DateCreated, DateDue, UserId) VALUES (".$classObj['id'].", ".$classObj['MeetingId'].", '".$classObj['MeetingName']."', '".$classObj['DateTimeFrom']."', ".$classObj['Length'].", '".$classObj['Room']."', '".$classObj['Venue'].", STR_TO_DATE(".$classObj['DateCreated'].", '%Y%m%d'), STR_TO_DATE(".$classObj['DateDue'].", '%Y%m%d'), '".$classObj['UserId']."');";

2 个答案:

答案 0 :(得分:0)

我认为在您的$query而不是$classObj['Venue']应该是$classObj['AppointmentList']['Venue']

答案 1 :(得分:0)

你的$ classObj是一个对象,而不是一个数组。在您的班级'约会列表'你应该定义一些方法来获得你在循环中设置的属性。

然后,当您将此信息插入数据库时​​,您可以像这样访问它:

$query = "REPLACE INTO AppointmentList (id, MeetingId,...etc...) VALUES ('"$classObj->get_id()."', ".$classObj->get_MeetingId()."');"; 

如果您要拥有多个对象,请创建一个数组以将对象放入其中。然后你可以将它们加载到你的数据库中,如下所示:

for($i=0; $i<sizeof($somearray);$i++){
$query = "REPLACE INTO AppointmentList (id, MeetingId,...etc...) VALUES ('"$somearray[$i]->get_id()."', ".$somearray[$i]->get_MeetingId()."');"; 
//SQL PDO insertion here

}

相关问题