Rotating around the axes

Hey–I’m fairly new to OpenGL, so I’d like some help since I can’t figure out what I’m doing wrong.

I have a 3D object, and I’m using the arrow keys on the keyboard to rotate it. The up/down arrow keys should rotate it vertically, whereas the left/right arrow keys should rotate it horizontally.

However, when I rotate it horizontally by (+/-)90 or (+/-)270 degrees and then try to use the up/down arrow keys to rotate it vertically, it should rotate it around the z-axis. Instead, it rotates around the x-axis.

I’ve also looked at my professor’s code and compared it to mine–they’ve got the same code rotation-wise, and I can’t figure out why mine is doing this.

Here’s the gist of my code, since I don’t want to paste the entire thing:

void special(int key, int x, int y)
{
   //  Right arrow - increase rotation by 5 degree
   if (key == GLUT_KEY_RIGHT)
      theta += 5;
   //  Left arrow - decrease rotation by 5 degree
   else if (key == GLUT_KEY_LEFT)
      theta -= 5;
   // Up key--rotate vertically
   else if (key == GLUT_KEY_UP)
      phi += 5;
   // Down key--rotate vertically
   else if (key == GLUT_KEY_DOWN)
      phi -= 5;
   theta %= 360;
   phi %= 360;
   //  Request display update
   glutPostRedisplay();
}

void display()
{
   // Clear screen
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   // Reset the transformations
   glLoadIdentity();
   // Set the viewing angles, rotate around the y and x axis respectively
   glRotated(theta,0.0,1.0,0.0);
   //if (theta == 90 || theta == 270 || theta == -90 || theta == -270)
      //glRotated(phi,0.0,0.0,1.0);
   //else
   glRotated(phi,1.0,0.0,0.0);

   if (toggle_axes == 1)
   {
      // Draw the axes in white
      glColor3ub(255, 255, 255);
      glBegin(GL_LINES);
      glVertex3d(0.0,0.0,0.0);
      glVertex3d(1,0.0,0.0);
      glVertex3d(0.0,0.0,0.0);
      glVertex3d(0.0,1,0.0);
      glVertex3d(0.0,0.0,0.0);
      glVertex3d(0.0,0.0,1);
      glEnd();
      // Label axes
      glRasterPos3d(1,0,0);
      Print("X");
      glRasterPos3d(0,1,0);
      Print("Y");
      glRasterPos3d(0,0,1);
      Print("Z");
   }
   // Flush, swapbuffers, etc.
}

glRotated(phi,1.0,0.0,0.0);

That code will only ever rotate phi degrees around the x-axis.
To rotate around multiple axis, you’d need to combine orientation matricies with these commands…

glRotated(phi,0.0,0.0,1.0); //phi on z-axis
glRotated(theta,1.0,0.0,0.0); //theta on x-axis