Reputation: 341
The Situation:
I have an Object which was transferred via AJAX to my PHP File which should insert one or more lines into my database.
In the PHP file I use json_decode to make my object work in PHP
$insertDatesArray = json_decode($_REQUEST['insertDatesArray']);
When I output this Object I get this in PHP:
object(stdClass)#2 (4) {
["alterstufe"]=>
array(3) {
[0]=> string(1) "1"
[1]=> string(1) "1"
[2]=> string(1) "1"
}
["sunday"]=>
array(3) {
[0]=> string(10) "14.09.2014"
[1]=> string(10) "21.09.2014"
[2]=> string(10) "28.09.2014"
}
["help1"]=>
array(3) {
[0]=> string(1) "6"
[1]=> string(1) "7"
[2]=> string(1) "8"
}
["help2"]=>
array(3) {
[0]=> string(1) "7"
[1]=> string(1) "8"
[2]=> string(1) "6"
}
}
This is the code, which generates my Object:
var date = new Array();
var alterstufen = new Array();
var helpperson1 = new Array();
var helpperson2 = new Array();
var elems2 = $('#plan tbody tr');
var count2 = elems2.length;
$('#plan tbody tr').each(function(){
alterstufen.push($('.pp-age').val());
date.push($('#pp-service-date', this).val());
helpperson1.push($('.selector-help1', this).val());
helpperson2.push($('.selector-help2', this).val());
});
var days = new Object();
days.alterstufe = alterstufen;
days.sunday = date;
days.help1 = helpperson1;
days.help2 = helpperson2;
var insertDatesArray = JSON.stringify( days );
The plan:
Now what I should have is this:
I need to insert every row (with one value from every object property) into my Database via PHP::PDO Right now i stuck at how I can set variables for every value.
My code looks like this right now:
foreach ($insertDatesArray as $obj => $val) {
$alterstufe = $val->alterstufe;
$date = $val->date;
}
The problem:
I don't know, how I can get the value from each object property to set them together and insert the data into my database.
Upvotes: 0
Views: 284
Reputation: 5899
You can do it like that:
$entriesCount = count($insertDatesArray->alterstufe);
for($i = 0; $i < $entriesCount; ++$i) {
var_dump($insertDatesArray->alterstufe[$i]);
var_dump($insertDatesArray->sunday[$i]);
var_dump($insertDatesArray->help1[$i]);
var_dump($insertDatesArray->help2[$i]);
// execute your query here with the data above
}
But as the first comment below your question tells you it's probably easier and cleaner to change the client side part.
So I would change the JS part instead to:
var data = new Array();
$('#plan tbody tr').each(function(){
data.push({
alterstufen: $('.pp-age').val()
date: $('#pp-service-date', this).val(),
help1: $('.selector-help1', this).val(),
help2: $('.selector-help2', this).val()
});
});
Then you get a nice all-in-one package at server side.
Upvotes: 2