You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP原生开发如何添加校验禁止用户使用相同账号重复注册

解决方案

校验逻辑需要放在Customer实体赋值、调用create()插入数据库之前,你之前报错大概率是把校验逻辑写在了插入之后,或者WHERE条件语法写得不对。

修改后的代码

function doInsert(){
global $mydb;

if(isset($_POST['submit'])){
    // 新增:先做账号重复校验
    $cusuname = trim($_POST['CUSUNAME']);
    // 转义防止SQL注入,$mydb->conn替换为你实际的数据库连接变量名即可
    $safe_cusuname = mysqli_real_escape_string($mydb->conn, $cusuname);
    // 校验查询,表名换成你实际的Customer对应表名
    $check_query = "SELECT CUSUNAME FROM tblcustomer WHERE CUSUNAME = '{$safe_cusuname}' LIMIT 1";
    $mydb->setQuery($check_query);
    $exist = $mydb->executeQuery();
    if(mysqli_num_rows($exist) > 0){
        echo "<script> alert('该账号已被注册,请更换后重试'); history.back(); </script>";
        exit;
    }

    $customer = New Customer(); 
    $customer->FNAME            = $_POST['FNAME'];
    $customer->LNAME            = $_POST['LNAME'];      
    $customer->CITYADD          = $_POST['CITYADD']; 
    $customer->GENDER           = $_POST['GENDER'];
    $customer->PHONE            = $_POST['PHONE']; 
    $customer->CUSUNAME         = $cusuname;
    $customer->CUSPASS          = sha1($_POST['CUSPASS']);  
    $customer->DATEJOIN         = date('Y-m-d H-i-s');
    $customer->TERMS            = 1;
    $customer->create();


    $email = trim($_POST['CUSUNAME']);
    $h_upass = sha1(trim($_POST['CUSPASS']));


    //it creates a new objects of member
    $user = new Customer();
    //make use of the static function, and we passed to parameters
    $res = $user->cusAuthentication($email, $h_upass);
                 
    if(!isset($_POST['proid']) || (isset($_POST['proid']) && empty($_POST['proid']))){
        echo "<script> alert('You are now successfully registered. It will redirect to Homepage. Enjoy our Coffee!'); </script>";
        redirect(web_root."index.php?q=home");
    }else{
        $proid = $_GET['proid'];
        $id = mysqli_insert_id(); 
        $query ="INSERT INTO `tblwishlist` (`PROID`, `CUSID`, `WISHDATE`, `WISHSTATS`)  VALUES ('{$proid}','{$id}','" . DATE('Y-m-d') . "',0)";
        $mydb->setQuery($query);
        $mydb->executeQuery();
        echo "<script> alert('You are now successfully registered. It will redirect to your profile. Enjoy our Coffee!'); </script>";
        redirect(web_root."index.php?q=profile");
    }
  }
}

额外优化建议

  • 数据库层给CUSUNAME字段添加唯一索引,就算代码逻辑遗漏也不会出现重复数据
  • 密码加密建议替换sha1为PHP原生的password_hash()方法,安全性更高
  • 所有接收的$_POST参数都建议做转义或者使用预处理查询,避免SQL注入风险

内容的提问来源于stack exchange,提问作者Hendriawan Yudhistira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:30:03