Jump to content

Help: Unable to get a student written to database more than once


belbin09

Recommended Posts

Hi, I am almost done my assignment however I am having an issue. I am trying to read enrolment and if the student is already registered for the course then print an error. However I am only able to register one student in one course each before getting the error message, which leads me to believe that it isn't reading the enrolment file properly. I seam to have an issue with this. Any help would be grateful. Thank you

 

// if the course is found and the student is found then check if they have registered
if ($found==3) {


  $equery= "SELECT * FROM enrolment WHERE uid ='$number' AND code = '$course'";
  $eresult= mysqli_query($link, $equery);


  while ($erow = mysqli_fetch_array($eresult)) {
  if ($erow['code'] == $course && $number == ($erow['uid'])) {


  
    } // if ($erow['code'] == $course && $number == ($erow['uid']))
  } // while ($erow = mysqli_fetch_array($eresult))
} // if ($found==3)


//if the student isn't registered in the course


$equery = "INSERT INTO enrolment(uid,code) VALUES ('$number','$course')";


if (mysqli_query($link, $equery)) {
  echo "New record created successfully";
}// if (mysqli_query($link, $equery))
else {
  echo "Error: You have already registered for the course";
} // else echo "Error: " .$link->error;


mysqli_close ($link);

 

Link to comment
Share on other sites

The logic of your script is wrong. Here's how the proper logic should look like:

 

<?php


// if the course is found and the student is found then check if they have registered
if ($found==3)
    {
    $equery= "SELECT * FROM enrolment WHERE uid ='$number' AND code = '$course'";
    //NOW YOU NEED TO COUNT THE NUMBER OF RETURNED RESULTS
  
    if ($NUMBER_OF_RETURNED_RESULTS>0)
        {
        echo "Error: You have already registered for the course";
        }
    else
        {
        //RUN QUERY TO INSERT DATA
        //IF QUERY SUCCEDED, DISPLAY SUCCESS MESSAGE 'New record created successfully'
        }
    }

 

As you see, I didn't post the whole code, but you get the idea. Also, be aware that the way you use MySQL queries now is very risky, since anyone could hack your database.

Link to comment
Share on other sites

Make the primary key on both columns

PRIMARY KEY (uid, code)
Now you can have as many records for a student as you want but you won't be allowed to add a course twice for the same student.

 

This also saves you having to do the select query first. Just insert the student/code combination. If you get a "duplicate key" error you can warn them they are already enrolled.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.