Search code examples
phpmysqlsqlinsertrestrict

How to restrict values in MySQL insert?


So I have a simple database exercise at school and I'm nearly finished but I don't know how to restrict values.

I have a database like:

ID | Name | Age
 1 | John | 20
 2 | Jack | 30

And so on.

Is there a way to prevent users from inserting an age lower than 18? I've been searching a lot and didn't find the answer... Thanks in advance!


Solution

  • With PHP, you can validate the form with something like:

    $enteredAge = 17; //from the user
    
    $minAge = 18;
    $maxAge = 125; //debatable
    
    if( !in_array( $enteredAge, range( $minAge, $maxAge) ) ){
        //Incorrect age.
    }
    

    If you feel as though an array is too "expensive" for this type of thing:

    $enteredAge = 17; //from the user
    
    $minAge = 18;
    $maxAge = 125; //debatable
    
    if($enteredAge < $minAge || $enteredAge > $maxAge){
        //Incorrect age.
    }