Grab piece of text in php

Asked

Viewed 64 times

0

I have a return of any error in php, for example.

QLSTATE[23000]: Integrity Constraint Violation: 1062 Duplicate entry

I wish I could get that specific code in case the 1062, recalling that the getCode of Exception he would return the 23000.

I want to know how to know if this particular section is contained in this string.

  • Depending on the library you are using, the error code is already assigned the exception (Inner Exception) or the driver error. Which library you are using (PDO, Mysqli, etc...)?

3 answers

2


You can do it like this:

$erro = "QLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry";
$estaContido = (strpos($erro, "1062") !== false);

var_dump($estaContido); // true
  • This solution of yours suits me, was worth Brow

2

If you are using PDO, there is no need to perform the parse of string. The specific error comes "embedded" in Exception and in the driver connecting.

PDO - Errors and error Handling

PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are Responsible for Mapping their Native codes to the appropriate SQLSTATE codes. The PDO::errorcode() method Returns the single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO::errorInfo() method which Returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.

PDO::errorInfo() or Pdoexception->errorInfo

try
{
   /** seu insert **/
}
catch (PDOException $exception)
{
    echo $exception->errorInfo[1];

    //ou

    var_dump($pdo->errorInfo());
}
  • 1

    Very good Gabriel +1

  • I like the solution, @Gabriel

  • but it’s not quite this 23000 that I want to catch, I wanted to catch the 1062

  • 1

    @gabrielfalieri is also important to know that the code 23000 is for integrity violation and 1062 is one of the types of violations. The code var_dump($pdo->errorInfo()); should bring you a list similar to [0 => "23000" , 1 => 1062 , 2 => "Duplicate entry"] Valide if it is in the correct key.

  • @gabrielfalieri https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_dup_entry

0

Can use preg_match so you can catch any error code, beyond the error 1062, an example assuming you are using mysqli:

if (!...) { //if que falhou
     $error = $mysqli->error;
     $code = 0;
     if (preg_match('#Q[^\[]+\[\d+\]:[^\d]+(\d+)\s#', $error, $matchs)) {
          $code = $matchs[1]; //Pega o código extraído da string
     } else {
          $code = $mysqli->errno; //Pega o código do QLSTATE se não conseguir obter nada com preg_match
     }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.