我正在尝试在我的应用程序中注册用户,我尝试检查年龄是否存在然后停止注册过程,我编写了代码来注册用户并且工作得很好,但是当我尝试使用 check_age 函数验证注册时它不能很好地工作,即使年龄存在,仍然允许注册,任何人都可以告诉我我的代码缺少什么: 这是我的代码:
<?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';
}
最佳答案
正如上面提到的评论,需要进行一些 sanitizer 。
但这就是我的建议..
更改
check_age()
函数并在其中传递年龄参数,如下所示,并返回$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); }
然后在
creat_Student()
函数中if
条件将发生变化,例如...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"; }
谢谢杰伊。
关于PHP检查现有值后插入到MYSql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39638543/