verify if the user is of legal age

1

I would like to try to verify before being able to make an insert if the users to register is of legal age can register in the system, but if it is a minor the system will not let it register, since it is required to be of legal age to be able to register.

insertion process

<!-- proceso para registrar-->
<?php
if(isset($_POST['guardar'])){


if($_POST['pass']!=$_POST['pass2']) { 

           $errMSG = "¡ Ups Aviso: Las Contraseñas deben coincidir !";
              header("refresh:5;registrarse.php");


  }else { 


  $sql = "SELECT cedula FROM usuarios WHERE cedula = :cedula LIMIT 1"; //Creamos la select
  $check = $DB_con->prepare($sql); //Preparamos la SELECT, de ésta manera evitamos SQL Injection
  $check->bindParam(':cedula', $_POST['cedula']);//Substituimos las variables de la SELECT
  $check->execute();//Ejecutamos la consulta
  $contador = $check -> rowCount();//Esta función devuelve el número de resultados que ha devuelto la SELECT
  if ($contador > 0) {
  $check->closeCursor();

          $errMSG = "¡ Ups Aviso: Este usuario ya se encuentra registrado !";
              header("refresh:5;registrarse.php");
  }


  //avisame si el nombre de usuario existe
  $sql = "SELECT id_usuarios FROM usuarios WHERE user = :user LIMIT 1"; 
  //Creamos la select
  $user_check = $DB_con->prepare($sql); //Preparamos la SELECT, de ésta manera evitamos SQL Injection
  $user_check->bindParam(':user', $_POST['user']);
  $user_check->execute();
  if($user_check->rowCount() > 0){
  $user_check->closeCursor();


  $errMSG = "¡ Aviso: El nombre de usuario ya se encuetra registrado !";
  header("refresh:5;registrarse.php");


  }


  $sql= "SELECT edad FROM usuarios WHERE user = :user LIMIT 1"; //Creamos la select
  $check = $DB_con->prepare($sql); //Preparamos la SELECT, de ésta manera evitamos SQL Injection
  $check->bindParam(':edad', $_POST['edad']);//Substituimos las variables de la SELECT
  $check->execute();//Ejecutamos la consulta
  $edad = $check->fetchColumn();
  $edad=$_POST['edad'];

  if ($edad > 18){
  $check->closeCursor();


     $errMSG = "¡ Aviso: no se permiten registros a menores de edad !";
       header("refresh:5;registrarse.php");

  }

  else
  {

  $sql=$DB_con->prepare("INSERT INTO usuarios (user,pass,idnivel,cedula,nombres,apellidos,fecha_nac,edad,cod,telefono,direccion,id_seguros,id_servicios,observaciones) 
  VALUES (:user,:pass,:idnivel,:cedula,:nombres,:apellidos,:fecha_nac,:edad,:cod,:telefono,:direccion,:id_seguros,:id_servicios,:observaciones)");
  $sql->bindParam(':user', $_POST['user']);
  $sql->bindParam(':pass', $_POST['pass']);
  $sql->bindParam(':idnivel', $_POST['idnivel']);
  $sql->bindParam(':cedula', $_POST['cedula']);
  $sql->bindParam(':nombres', $_POST['nombres']);
  $sql->bindParam(':apellidos', $_POST['apellidos']);
  $sql->bindParam(':fecha_nac', $_POST['fecha_nac']);
  $sql->bindParam(':edad', $_POST['edad']);
  $sql->bindParam(':cod', $_POST['cod']);
  $sql->bindParam(':telefono', $_POST['telefono']);
  $sql->bindParam(':direccion', $_POST['direccion']);
  $sql->bindParam(':id_seguros', $_POST['id_seguros']);
  $sql->bindParam(':id_servicios', $_POST['id_servicios']);
  $sql->bindParam(':observaciones', $_POST['observaciones']);
  $sql->execute();

      $successMSG ="¡ Bien Hecho: Usuario registrado correctamente !";
            header("refresh:5;login.php");
         }
      }
    }
  ?>
  <!-- fin proceso para registrar-->

function to calculate age

  <script>
  function calcAge(dateString) {
    var birthday = +new Date(dateString);
    return ~~((Date.now() - birthday) / (31557600000));
}

function add_months(datestr, months) {
    var new_d = new Date(datestr);
    new_d.setMonth(new_d.getMonth() + months);
    return new_d;
}

$(document).ready(function(){
$('select').material_select();
$(".button-collapse").sideNav();
$('.modal').modal();
$('.datepicker').pickadate({
        selectMonths: true, // Creates a dropdown to control month
        selectYears: 10, // Creates a dropdown of 15 years to control year
        format: 'yyyy-mm-dd', // formto de fecha  
        onClose: function() {
            $('#edad').val(calcAge($('#fecha_nac').val()));
        }
    });

 });
 </script>
    
asked by yoclens 04.08.2017 в 06:56
source

2 answers

2

Friend I leave this function to you to calculate the age without problems.

You can modify it so that it returns true or false and based on that you execute or not the insert query.

If you set it to return true or false with doing this, it would suffice:

if getAge($fecha)
{
   //Es mayor, insertar

}else{

   //No eres mayor, no te puedes registrar

}

Code: ver demo

<?php 


    /*
     *Calcular si es menor de 18 años
     *param: $fecha Fecha de nacimiento en el formato Y-m-d
    */

    / * Dos llamadas al método para probar * /
    getAge("1972-08-22");
    getAge("2015-07-22");


    function getAge ($fecha)
    {

        $mayor=18;

        //Creamos objeto fecha desde los valores recibidos
        $nacio = DateTime::createFromFormat('Y-m-d', $fecha);

        //Calculamos usando diff y la fecha actual
        $calculo = $nacio->diff(new DateTime());

        //Obtenemos la edad
        $edad=  $calculo->y;    

        if ($edad < $mayor) 
        {
            echo "Usted es menor de edad. Su edad es: $edad\n";
            //return false;  
         }else{
            echo "Usted es mayor de edad. Su edad es: $edad\n";
            //return true;  
        }
    }
?>

Resultado:

Usted es mayor de edad. Su edad es: 44
Usted es menor de edad. Su edad es: 2
    
answered by 04.08.2017 / 07:42
source
0

it would not be the other way around

if ($edad < 18)
{
   $check->closeCursor();
}

So that those who are under age will receive the message

    
answered by 04.08.2017 в 07:12