Saleh Refaai Saleh Refaai - 2 months ago 8
MySQL Question

PHP Insert to MYSql after checking existed value

I am trying to register users in my app and i tried to check if the age is existed then stop the registration process, I wrote my code to register users and worked very well but when I tried to validate the registration using check_age function it doesn't work well and still allow registration even if the age is existed can anyone tell me what is missed with my code :
here is my code:

<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
require "init.php";

creat_Student();
}
function creat_Student()
{
global $con;
$firstname=$_POST["firstname"];
$lastname=$_POST["lastname"];
$age=$_POST["age"];

if(strcmp(check_age(), '0') == 0)
{
$query="Insert Into student(firstname,lastname,age) values ('$firstname','$lastname','$age');";
mysqli_query($con,$query);
mysqli_close($con);
}
else
echo "not true";

}
function check_age()
{
global $con;
$age=$_POST["age"];
echo " $age";
$temp_arr=array();

$query="SELECT * FROM student where age ='{$age}'; ";
$result=mysqli_query($con,$query);
$num_of_rows=mysqli_num_rows($result);

if($num_of_rows==0)
return '0';
else
return '1';

}

Answer

Well as mention is comments above, there are some sanitizing needed.

But here is what i suggest..

  1. Change check_age() function and pass parameter of age in it as below and return $num_of_rows.

    function check_age($age)
    {
       global $con;
    
       $query="SELECT * FROM  student where age =".$age;
       $result=mysqli_query($con,$query);
       return mysqli_num_rows($result);
    }
    
  2. Then in creat_Student() function if condition will change like...

    function creat_Student()
    {
      global $con;
      $firstname=$_POST["firstname"];
      $lastname=$_POST["lastname"];
      $age=$_POST["age"];
    
      if(!check_age($age))
      {
        $query="Insert Into student(firstname,lastname,age) values ('$firstname','$lastname','$age');";
        mysqli_query($con,$query);
        mysqli_close($con);
     }
     else
        echo "not true";
    }
    

Thanks, Jay.

Comments