Storing an std Class Object in database

hi everybody!
I have the following std Class Object That I get from form values dynamically:
`

  std Class Object
(
[Course]=>Array
(
[0]=>std Class Object
(
[coursename]=>Course one     
)
[1] => std Class Object
(
[studentfirstname]=>Princess 
[studentlastname]=>Oka
[studentage]=>29
)
[2]=>std Class Object
(
[studentfirstname]=>Linda
[studentlastname]=>Bucha
[studentage]=>26
)
)
)

I need to store this object in two tables ‘courses’ and ‘students’ but I cannot get my code to work. I have the following code:

$course_name = "";
$studentfirstname = "";
$studentlastname= "";
$studentage = "";
$my_course = json_decode($_POST);
$course = $my_course->Course;
for($c = 0; $c < count($Course); $c++){ 
        foreach($course[$c] as $key=>$value){
            if($key == "coursename"){
                $course_name = $course[$c]->coursename;
            }
            if($key == "studentfirstname"){
                $studentfirstname = $course[$c]->studentfirstname;
            } 
            if($key == "studentlastname"){
                $studentlastname = $course[$c]->studentlastname;
            } 
            if($key == "studentage"){
                $studentage = $course[$c]->studentage;
            } 
        }
    }
    $query1 = "INSERT INTO courses (coursename)VALUES   ('$course_name')";
            if ($my_db_object->query($my_insert_query1) === true){
                $last_id = $my_db_object->insert_id;
                $good = "data saved ";
            }
            else{
                $bad = "Error: " .$query1.$my_db_object->error;
            }

     $query1 = "INSERT INTO courses (coursename)VALUES('$course_name')";
            if ($my_db_object->query($my_insert_query1) === true){
                $last_id = $my_db_object->insert_id;
                $good = "data saved ";
            }
            else{
                $bad = "Error: " .$query1.$object->error;
            }
        $query2 = "INSERT INTO students SET     
                        course_id = '".$last_id."',
                        studentfirstname = '".$studentfirstname."',
                        studentlastname = '".$studentlastname."',
                        studentage = '".$studentage."';
        if ($object->query($query2) === true) {
                $good = "data saved ";
        } 
        else {
                $bad = "Error: " .$query2.$object->error;
        }

Please help me I cannot store all my students just one.

I am not sure what the standard object has to do with it, but if your students are a group of people within a course, you have no loop in your insertion logic to account for them. You are only looping through courses.

Scott

1 Like

Thank you for your answer.I know I still need to loop but I really do not know what else to do than to put the insertion queries inside the for loop and of course it produces duplicate values.

Then you need to consider doing upserts.

http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

Scott

1 Like

Also note this bit of code:

$course = $my_course->Course;
for($c = 0; $c < count($Course); $c++){ 

In particular, $course in the first line is not the same as $Course in the second, and I can’t see anywhere that you define the latter. So your count() would probably return zero and never run through the loop.

You also close that for() loop before you start running any of the queries - is that intentional? That may be why it only stores a single row. And there’s a missing quote at the end of your definition of $query2 that I am surprised doesn’t trigger a parse error. And why do you define and execute $query1 twice?

1 Like

Hi I am sorry but I did not add the first lines of my code but it works. Sorry for the typos but my code does work just that it does not store all the students. The reason I did not include the queries in the body of the for loops is that they make data to be stored anyhow and skip fields which I do not want.

OK, but it’s difficult to help figure out why code doesn’t work if the code you post is not the actual code that you are having trouble with, or if there are significant parts of it missing. I still don’t understand why you define and run the first query twice, though.

1 Like

You only have one set of variables for students, so you can only record one student at a time, and that won’t work. If you want to insert multiple students you need an array. So, something like:

$coursename = '';
$students = [];
$course = $main->Course;
foreach ($course as $courseInfo) {
  if (property_exists($courseInfo, 'coursename')) {
    // ideally check here if a coursename was already set, error if it was
    $coursename = $courseInfo->coursename;
  } else if (
  	   property_exists($courseInfo, 'studentfirstname')
  	&& property_exists($courseInfo, 'studentlastname')
  	&& property_exists($courseInfo, 'studentage')
  	) {
    $students[] = [
      'firstname' => $courseInfo->studentfirstname,
      'lastname' => $courseInfo->studentlastname,
      'age' => $courseInfo->studentage
    ];
  } else {
     // unknown input -> log error and continue, or stop processing, depending on your needs
  }
}

so you end up with a variable $coursename that contains the name of the course and an array $students that looks like this

array (
  0 => 
  array (
    'firstname' => 'Princess',
    'lastname' => 'Oka',
    'age' => 29,
  ),
  1 => 
  array (
    'firstname' => 'Linda',
    'lastname' => 'Bucha',
    'age' => 26,
  ),
) 

which you can then easily loop and store in the database one by one.
You could also incorporate this in your main loop, but that would dilute the waters because you’re doing two things at once, namely parsing the JSON result and storing it in the database.
If you split this in two sections, so parsing first and then insert it in the database the code is a lot cleaner and easier to follow.

1 Like

Thanks a million ScallioXTX it works now.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.