我尝试验证注册表单中的字段(密码匹配)未使用UserID和电子邮件。
这是我的代码
<?php
if(isset($_POST['submit'])){
$msg="";
$id="";
$name=$_POST['cName'];
$address=$_POST['cAddrss'];
$country=$_POST['cCountry'];
$mobil=$_POST['cTel'];
$sex=$_POST['cSex'];
$email=$_POST['cEmail'];
$userName=$_POST['cUsername'];
$userPassword=$_POST['cPassword'];
$confPassword=$_POST['concPassword'];
$checkEmail=$db->query("select * from users where email ='".$email."'");
$checkUID=$db->query("select * from users where user_name ='".$userName."'");
if($userPassword !== $confPassword)
{
$msg="Password don't match";
}
if($checkEmail -> num_rows == 1)
{
$msg = "<span style='color:#F00; font-size:14px; font-weight:bold;'>This email already taken</span>";
}
if($checkUID -> num_rows == 1)
{
$msg = "<span style='color:#F00; font-size:14px; font-weight:bold;'>This User name already taken</span>";
}
if($put=$db->prepare("INSERT INTO users(id, name, mobile, sex, country, address, user_name, user_password, email)VALUE(?, ?, ?, ?, ?, ?, ?, ?, ?)"))
{
$put->bind_param('issssssss', $id, $name, $mobil, $sex, $country, $address, $userName, $userPassword, $email);
$put->execute();
$put->close();
}
else
{
die($db->error);
}
header("Location:index.php?pid=3&smsg=smsg");
}
?>
表单会忽略我的验证并跳转到标题并将其发送到成功页面,因为一切都很好。
在我的表单顶部,如果有$msg
<?php if(!empty($msg)) {echo $msg;} ?>
答案 0 :(得分:0)
尝试这种方法:
if($userPassword !== $confPassword){
$msg.="Password don't match";
}else{
//Password matches, now we can hit the database
$checkEmail=$db->query("select * from users where email ='".$email."'");
$checkUID=$db->query("select * from users where user_name ='".$userName."'");
$emailExist =($checkEmail -> num_rows > 0);
$userNameExist = ($checkUID -> num_rows > 0);
if(!$emailExist && !$userNameExist){
$put=$db->prepare("INSERT INTO users(id, name, mobile, sex, country, address, user_name, user_password, email)VALUE(?, ?, ?, ?, ?, ?, ?, ?, ?)");
$put->bind_param('issssssss', $id, $name, $mobil, $sex, $country, $address, $userName, $userPassword, $email);
if($put->execute()){
//record Inserted now redirect
$msg .= "Success! no validation error";
header("Location:index.php?pid=3&smsg=smsg");
}else{
//error
$msg = "error while INSERT";
die($db->error);
}
}else{
//found record
$msg.= $emailExist ? "This email already taken" : "";
$msg.= $userNameExist ? "This User name already taken" : "";
}
}
echo $msg;