PHP.mk документација

PDOException

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

class.pdoexception.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека class.pdoexception.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
PDOException

Референца за `class.pdoexception.php` со подобрена типографија и навигација.

class.pdoexception.php

PDOException класа

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Вовед

Претставува грешка предизвикана од PDO. Не треба да фрлате PDOException од вашиот код. Погледнете Исклучоци за повеќе информации за Исклучоци во PHP.

Синопсис на класата

class PDOException extends RuntimeException {
/* Својства */
protected int|string $code;
public ?array $errorInfo (PHP 7, PHP 8);
/* Наследени својства */
protected string $message = "";
private string $string = "";
protected string $file = "";
protected int $line;
private array $trace = [];
/* Наследени методи */
public Exception::__construct(string $message = "", int $code = 0, ?Проверува тврдење $previous = null)
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
}

Својства

errorInfo

Соодветствува на Пример #1 Преземање на SQLSTATE код or - Преземи го SQLSTATE поврзан со последната операција на рачката на изјавата

code

SQLSTATE код за грешка. Користете (PHP 5 >= 5.1.0, PHP 7, PHP 8) за да пристапите до него.

Белешки од корисници 3 белешки

Typer85 на gmail точка com
пред 16 години
Here is something interesting regarding a PDOException and it involves some of the annoyances that can be associated with PHP's dynamic nature.

PDOException extends from RuntimeException, which in return extends from Exception. As such, it has access to the $code Protected Class Variable, which represents the Exception's code as an Integer (duh!) and can be accessed externally using the Exception::getCode Method.

Here is the interesting part. PDOException actually redefines $code as a String and not an Integer because for its case, $code actually contains the Exception's SQL State, which is composed of characters and numbers.

It is actually documented in the manual that $code is a String and not an Integer but it might not be immedietley clear because it is hidden by the fact that PDOException::getCode is documented to return an Integer and not a String!

Some developers like to catch a PDOException and rethrow it as a different Exception if they wrap their database calls in an external library. For example, consider the following code:

<?php

try {
    $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException.
}
catch( PDOException $Exception ) {
    // PHP Fatal Error. Second Argument Has To Be An Integer, But PDOException::getCode Returns A
    // String.
    throw new MyDatabaseException( $Exception->getMessage( ) , $Exception->getCode( ) );
}

?>

Be careful in that you have to typecast the value returned by PDOException::getCode to an Integer BEFORE you pass it as an Argument to your Exception's Constructor. The following will work:

<?php

try {
    $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException.
}
catch( PDOException $Exception ) {
    // Note The Typecast To An Integer!
    throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) );
}

?>

Hope this will save some developers some frustrating hours from an otherwise enjoyable job :)

Good Luck,
Exception::getCode()
пред 15 години
PDOException has two methods for retrieving information about an error. When interpreting the PDOException I run into a problem, the error code that is provided by getCode() is meaningless.  I have come up with a method to make both the error code and message more usable.

A bad username or password would normally provide the following:

CODE : 0
Message : "SQLSTATE[28000] [1045] Access denied for user 'user'@'example.com' (using password: YES)"

Using my extended exception class provides:

CODE: "28000"
Message: "Access denied for user 'user'@'example.com' (using password: YES)"

<?php
class pdoDbException extends PDOException {

    public function __construct(PDOException $e) {
        if(strstr($e->getMessage(), 'SQLSTATE[')) {
            preg_match('/SQLSTATE\[(\w+)\] \[(\w+)\] (.*)/', $e->getMessage(), $matches);
            $this->code = ($matches[1] == 'HT000' ? $matches[2] : $matches[1]);
            $this->message = $matches[3];
        }
    }
}
?>

To walk threw the method; first the beginning of the message is checked for the SQLSTATE text.  If the text is present, message is then parsed to pull the ANSI code, the SQL specific code, and the message.  The parsed values are stored in there respective variables.  The error code variable stores the ANSI code, unless ANSI is 'HT000' (unmapped error code) then SQL specific code is used.

Using this class is easy; when interacting with PDO use a try catch set of blocks, as follows:

<?php
try {
    $pdo = new PDO($dns, $username, $password, $options);
} catch (PDOException $e) {
    throw new pdoDbException($e);
}
?>

Now you can use the normal error methods to retrieve the real error code and message.

<?php
echo $err->getCode(); // Outputs: "28000"
echo $err->getMessage(); // Outputs: "Access denied for user 'user'@'example.com' (using password: YES)"
?>

If you decide to use this code, be aware that the error code is a string (as apposed to PHP standard errors which are integers) as some error codes are alphanumeric.
samuelelliot+php dot net at gmail dot com
пред 11 години
Since PDOException returns the error code as a string, you need a constructor like the one below if you wish to rethrow the PDOException as a custom exception.
This constructor does not call the parent::__construct which will enforce the int type on the error code, but set the message and code as properties directly on the custom exception object.

<?php

class CustomException extends PDOException {
    
    /**
     * Override constructor and set message and code properties.
     * Workaround PHP BUGS #51742, #39615
     */
    public function __construct($message=null, $code=null) {
        $this->message = $message;
        $this->code = $code;
    }
    
}
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.