How to show different messages when entering duplicate data to the database? Php / MySql

2

Hello!

I am trying that, when the user enters the name of a region, if the same one is repeated it will be shown in the screen "An error occurred", but I can not.

Region.php:

class Region
{
    private $regID;
    private $regNombre;

    private function cargarDatosDesdeForm()
    {

          if(isset($_POST["regID"]))
          {
              $this->setRegID($_POST["regID"]);
          }

          if(isset($_POST["regNombre"]))
          {
              $this->setRegNombre($_POST["regNombre"]);
          }
     }

       public function agregarRegion()
       {
            $this->cargarDatosDesdeForm();

            $link = Conexion::conectar();

            $sql = "INSERT INTO regiones(regNombre) VALUES (:regNombre)";

            $stmt = $link->prepare($sql);

            $regNombre = $this->getRegNombre();

            $stmt->bindParam(":regNombre",$regNombre,PDO::PARAM_STR);

            if($stmt->execute())
            { 
                return true;
            }
          return false;
       }
}

addRegion.php:

<?php 
   require "clases/Conexion.php";
   require "clases/Region.php";

     $objRegion = new Region();

      $objRegion->agregarRegion();

         if($objRegion){
 ?>
         <p>Region agregada</p>
    <?php }else{ ?>

      <p>Lo siento,ocurrio un error.</p>

          <?php /*if('codigo de error==666'){ //Con el codigo de error mostrar esto:
                     <p>Ya hay una region con ese nombre.</p>
                   }*/?>


  <?php } ?>

But what I see on the screen is the following:

  

Warning: PDOStatement :: execute (): SQLSTATE [23000]: Integrity constraint violation: 1062 Duplicate entry 'America' for key 'regName' in C: \ xampp \ htdocs \ test \ classes \ Region.php on line 60

     

Region added

  • How can I avoid the error message?

  • How can I do so that if there is an error, Region Added does not appear, but "Did an error occur"?

  • And what about the mysql error code to know if the error is that the name is repeated?

PS: The RegName field is unique.

    
asked by Ale 24.03.2018 в 20:02
source

1 answer

1

Hello colleague, I hope you serve or orient

  try {
  $sql = "INSERT INTO regiones(regNombre) VALUES (:regNombre)";

         $stmt = $link->prepare($sql);

         $regNombre = $this->getRegNombre();

         $stmt->bindParam(":regNombre",$regNombre,PDO::PARAM_STR);
         $stmt->execute();
} catch (\PDOException $e) {
      if ($e->getCode() === 23000) { // numero del error para Duplicate entry '%s' for key %d 
          //hacer algo
     }
}

link

link

    
answered by 24.03.2018 в 23:06