从mysql数据库在php中重复值验证

时间:2017-02-03 08:18:38

标签: javascript php html mysql validation

我想在SQL数据库中检查reg_no是否重复,并显示错误消息"请输入唯一的Reg。否"

这是我的代码:

<?php
error_reporting( ~E_NOTICE );
require_once 'dbconfig.php';
if(isset($_POST['btnsave']))
{
    $name       = $_POST['name'];
    $reg_no     = $_POST['reg_no'];
    $imgFile    = $_FILES['photo']['name'];
    $tmp_dir    = $_FILES['photo']['tmp_name'];
    $imgSize    = $_FILES['photo']['size'];

    if(empty($name)){
        $errMSG = "Please Enter Student Name.";
    }
    else if(empty($reg_no)){
        $errMSG = "Please Enter Registration Number.";
    }
    else if(empty($imgFile)){
        $errMSG = "Please Select Image File.";
    }
    else
    {
        $upload_dir = 'photos/';
        $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
        $valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
        $photo = rand(1000,1000000).".".$imgExt;
        if(in_array($imgExt, $valid_extensions)){           
            if($imgSize < 5000000)              {
                move_uploaded_file($tmp_dir,$upload_dir.$photo);
            }
            else{
                $errMSG = "Sorry, your file is too large.";
            }
        }
        else{
            $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";        
        }
    }
    if(!isset($errMSG))
    {
        $stmt = $DB_con->prepare('INSERT INTO tbl_users(name,reg_no,photo) VALUES(:name, :reg_no, :photo)');
        $stmt->bindParam(':name',$name);
        $stmt->bindParam(':reg_no',$reg_no);
        $stmt->bindParam(':photo',$photo);
        if($stmt->execute())
        {
            $successMSG = "new record succesfully inserted ...";
            header("refresh:5;index.php");
        }
        else
        {
            $errMSG = "error while inserting....";
        }
    }
}
?>

1 个答案:

答案 0 :(得分:0)

以下是更新的更改

$stmt = $DB_con->prepare('select count(*) as cnt from tbl_users where reg_no) VALUES(:reg_no);
$stmt->bindParam(':reg_no',$reg_no);
$stmt->execute();
$stmt->bind_result($cnt);
if($cnt>0){
  echo $errMSG = "Please enter unique Reg. No";
}
else{
  $stmt = $DB_con->prepare('INSERT INTO tbl_users(name,reg_no,photo) VALUES(:name, :reg_no, :photo)');
  $stmt->bindParam(':name',$name);
  $stmt->bindParam(':reg_no',$reg_no);
  $stmt->bindParam(':photo',$photo);
  if($stmt->execute())
  {
    $successMSG = "new record succesfully inserted ...";
    header("refresh:5;index.php");
  }
  else
  {
    $errMSG = "error while inserting....";
  }
}