如果可能重复输入,如何发出警告消息?

时间:2015-08-08 05:37:36

标签: php pdo

我这里有使用PDO插入的代码,并且插入工作正常我的问题是我怎么能确定我是否在文本框中输入已经在数据库中的记录,在我的数据库中我有一列ID ,名字和姓氏,ID是自动增量,Firstname设置为唯一,最后是密码设置为varchar ..我想要发生的是当尝试插入已经在数据库中的记录我想要一条警告消息或者一条警告信息,告诉我"记录已经重复" ..有人可以帮我吗?

这是代码     的 class.php

 public function create($username,$password,$province)
 {
 try
 {
 $stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname)  VALUES(:Firstname, :Lastname)");
  $stmt->bindparam(":Firstname",$Firstname);
  $stmt->bindparam(":Lastname",$Lastname);
  $stmt->execute();
  return true;

  }
  catch(PDOException $e)
  {
  echo $e->getMessage();  
  return false;
  }
  }

,这是index.php

  <?php
  include_once 'dbconfig.php';

  if(isset($_POST['btn-save']))
  {
  $username = $_POST['Firstname'];
  $password = $_POST['Lastname'];

  if($crud->create($Firstname,$Lastname))
  {
  echo "<script type='text/javascript'>alert('Saved!');</script>";
  }
  else
  {
  echo "<script type='text/javascript'>alert('Insertion Failed!');  </script>";
  }  
  }
  ?>

  <form method="POST" class="signin" action="" name="Add" target="iframe">
    <fieldset class="textbox">
    <label class="username">
        <span>Username</span>
            <input id="Firstname" name="Firstname" value="" type="text" placeholder="Username" required/>
    </label>
    <label class="password">
        <span>Password</span>
            <input id="Lastname" name="Lastname" value="" type="password" Placeholder="Password" required/>
    </label>

    <br />
    <button id="submit" type="submit" name="btn-save">Save</button> 
    <button id="submit" type="reset" name="reset">Reset</button>
    <br />
    <br />
    <hr>
         </fieldset>
   </form>

1 个答案:

答案 0 :(得分:1)

如果您在数据库中设置了正确的UNIQUE键,PDO就会抛出这样的警告/错误。您可以通过插入两次相同的名称轻松自己尝试

您应该尝试将代码更改为此,因为这会抛出实际错误。正确的调用函数是PDOStatement::errorInfo

示例代码如下:

public function create($username,$password,$province)
{
   try
   {
      $stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname)  VALUES(:Firstname, :Lastname)");
      $stmt->bindparam(":Firstname",$Firstname);
      $stmt->bindparam(":Lastname",$Lastname);

      if (!$stmt->execute())
      {
          throw new Exception('Could not execute SQL statement: ' . var_export($stmt->errorInfo(), TRUE));   
      }
      return true;

  }
  catch(Exception $e)
  {
      // Here you can filter on error messages and display a proper one.
      return $e->getMessage();
  }
}

在index.php中,将PHP代码更改为:

if(isset($_POST['btn-save']))
{
    $username = $_POST['Firstname'];
    $password = $_POST['Lastname'];

    $result = $crud->create($Firstname,$Lastname);
    if($result === TRUE)
    {
        echo "<script type='text/javascript'>alert('Saved!');</script>";
    }
    else
    {
        echo "<script type='text/javascript'>alert(" . $result . ");  </script>";
    }  
}

另一种更好的方法是在执行实际插入之前单独执行 SELECT ,以查看您尝试插入的值是否已存在。