duanhuiqing9528 2017-03-04 10:47
浏览 30
已采纳

表单验证不起作用

I want to display the error if user entered a duplicate name. But, it's not working. It keeps the name inserted even it's same. So, here is my code :

$namaErr = "";
$error==false;
if (isset($_POST['btnSubmit'])) {
if(isset ($_POST['nama'])){
$nama = $_POST['nama'];
$query ='SELECT nama FROM daftar_pengguna WHERE nama="' . $nama . '" LIMIT 
1';
$result = mysqli_query($query);
$totalNumRowResult = mysqli_num_rows($result);
if($totalNumRowResult > 0){
$error=true;
$namaErr="Nama ini telah digunakan!!";
} 
}

If no error, it will inserted in database :

else{
$query="INSERT INTO daftar_pengguna(nama) VALUES 
('$nama')";
$res = mysqli_query($query);
header('Location:index.php?registered=true');  
}    
}

I've searched all question like mine but, no luck.

  • 写回答

3条回答 默认 最新

  • duanguoping2016 2017-03-04 11:03
    关注

    I suggest two things:

    1. Merge the if conditions to one block , this will remove the braces confusion had as I noted in above comment and also noted by Sujith.

    2. Also I suggest you sanitize the $_POST variable before sending to Database query...

    See code below with the suggested modifications:

    <?php
    
    $namaErr = "";
    $error = false;
    
    # Merge condition checks in One block using && (AND)
    if (isset($_POST['btnSubmit']) && isset($_POST['nama'])) {
    
    $nama = $_POST['nama'];
    
    # Sanitize the input before running into Database query
    $nama = filter_var($nama, FILTER_SANITIZE_STRING);
    
    
    $query ='SELECT nama FROM daftar_pengguna WHERE nama="' . $nama . '" LIMIT 
    1';
    $result = mysql_query($query);
    $totalNumRowResult = mysql_num_rows($result);
    
    if($totalNumRowResult > 0){
      $error=true;
      $namaErr="Nama ini telah digunakan!!";
    } 
    else{
      $query="INSERT INTO daftar_pengguna(nama) VALUES ('$nama')";
      $res = mysql_query($query);
      header('Location:index.php?registered=true');  
    }
    }    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答