Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

php - How to check whether inserting fails?

Here is my script:

try {

    $stmt = $db_con->prepare(" INSERT INTO mytable ( col ) VALUES ( ? ) ");
    $inserting = $stmt->execute( array('anything') );

    if ( $inserting ) {
        echo 'successful';

    } else {
        echo 'failed';
    }

} catch(PDOException $e){ 

    echo 'failed';
}

What's my question: All I want to know, else and catch are the same in my script? In other word when else executes?

I think else never executes, because if $inserting == false then it jumps to the catch block, then else never run. Am I right? Writing that else is useless?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It depends.

Most of time you don't want to know if a particular insert failed. But rather if your site is working all right or not. So in general your code should be just

$stmt = $db_con->prepare(" INSERT INTO mytable ( col ) VALUES ( ? ) ");
$stmt->execute( array('anything') );
echo 'successful';

with both else and catch being useless.

However, sometimes you may want catch a certain error. In this case use catch. Here is a code from my article:

try {
    $pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data);
} catch (PDOException $e) {
    if ($e->getCode() == 1062) {
        // Take some action if there is a key constraint violation, i.e. duplicate name
    } else {
        throw $e;
    }
}

here you may catch a certain error and handle it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...