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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…