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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀