catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.83k stars 1.15k forks source link

How can I check the result if unsuccessful? #604

Closed imcsd closed 3 years ago

imcsd commented 7 years ago

Medoo doesn't return a error when the database operation is unsuccessful.

ghost commented 7 years ago

i'm wondering the same... I know there's several ways to check it but i don't know what is the perfect way: Where there is no error error() is :

$database->error()[0] = "00000"
$database->error()[1] = NULL
$database->error()[2] = NULL

... so testing the result with error() could have 1, 2, 3 of thoses values ? Actually i check only the error()[1] === NULL but hope that it doesnt change in the future !

Nicero commented 5 years ago

You may handle errors with try - catch:

try {
    $database = new Medoo([
        'database_type' => 'mysql',
        'database_name' => 'xxx',
        'server' => 'yyy',
        'username' => 'kkk',
        'password' => 'www',
        'charset' => 'utf8',
        'option' => array(
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
        )
    ]);
} catch (Exception $e) {
    $error = 1;
    // No connection
}   

and

try {
    $database->insert("mytable", $insertArray);
} catch (Exception $e) {
    $error = 1;
    // Error during INSERT operation
}
ion-ciubaciuc commented 4 years ago

i'm wondering the same... I know there's several ways to check it but i don't know what is the perfect way: Where there is no error error() is :

$database->error()[0] = "00000"
$database->error()[1] = NULL
$database->error()[2] = NULL

... so testing the result with error() could have 1, 2, 3 of thoses values ? Actually i check only the error()[1] === NULL but hope that it doesnt change in the future !

The $database->error() has the code: return $this->statement ? $this->statement->errorInfo() : null;.

$this->statement is an instance of PDOStatment.

$this->statement->errorInfo() is the same as PDO::errorInfo and returns an array with 3 elements.

Reading the documentation on PHP website you'll see a note:

If the SQLSTATE error code is not set or there is no driver-specific error, the elements following element 0 will be set to NULL.

so using $database->error()[1] === NULL to check for errors is safe.