Take piece of text in php

0

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

  

QLSTATE [23000]: Integrity constraint violation: 1062 Duplicate entry

I wanted to be able to get this code specific, in this case the 1062 , remembering that getCode of Exception it would return 23000 .

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

    
asked by anonymous 02.06.2017 / 21:04

3 answers

2

You can do this:

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

var_dump($estaContido); // true
    
02.06.2017 / 21:13
2

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

PDO - Errors and error handling

  

PDO standardizes on using SQL-92 SQLSTATE error code strings;   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());
}
    
02.06.2017 / 21:20
0

You can use preg_match so you can get any error code , plus 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
     }
}
    
02.06.2017 / 21:23