Saving form values to an Object as attributes (Associative Array, PHP, PDO, lunk head)

52 views Asked by At

I'm working on an AJAX CRUD and I cannot get the form values in the Assoc. array to save individually as object attributes for the MySQL query.

I am following enter link description here but instead of the mysqli I'm using PDO.

Not much of a php person and this is my first OOP use of PDO and JSON.

The vardump() shows the input text is there...

// get posted data
$data = json_decode(file_get_contents("php://input"), true);

// set event property values
$event=>mainTitle = $data->main-title;
$event->subTitle = $data->sub-title;
$event->eventUrl = $data->event-url;

And the dumps:

array(9) {
["main-title"]=>
string(15) "Test Main Title"
["sub-title"]=>
string(14) "Test Sub title"
["event-url"]=>
string(9) "Test URTL"
...

object(Event)#3 (11) {
["conn":"Event":private]=>
object(PDO)#2 (0) {
}
["table_name":"Event":private]=>
string(8) "tblEvent"
["mainTitle"]=>
int(0)
["subTitle"]=>
int(0)
["eventUrl"]=>
int(0)
...
3

There are 3 answers

1
arku On

You have passed a second argument to json_decode() what means you'd like to get an array instead of the object. So just work like with the array. Replace to $event->mainTitle = $data['main-title'];

0
Weyfarere On

I found the answer for part of my problem here: Handling-JSON-like-a-boss-in-PHP

json_decode() is able to return both an object or associative array.

//For an object: 
$result = json_decode($string);

//For an Assoc. Array: 
$result = json_decode($string, true);

What I struggled with is that the var_dump() returns almost exact result for the two. They indeed have to be the same type.

The second part of my problem that was more subvert was having hyphens in the object attribute names. I didn't find a reason why but for sake of clarity in my code I just removed them.

1
newbie On

try changing $event=>mainTitle to $event->mainTitle