如何检查是否插入失败? [英] How to check whether inserting fails?
问题描述
这是我的剧本:
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';
}
我的问题是什么:我想知道的所有内容else
和catch
在我的脚本中都相同?换句话说,什么时候执行else
?
What's my question: All I want to know, else
and catch
are the same in my script? In other word when else
executes?
我认为else
永远不会执行,因为如果$inserting == false
然后它跳到catch
块,那么else
永远不会运行.我对吗?写else
是没有用的吗?
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?
推荐答案
这要视情况而定.
大多数时候您不希望知道特定插入是否失败.但是,如果您的网站正常运行还是无法正常运行,则可以使用.因此,通常您的代码应该只是
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';
没有其他收获和收获.
但是,有时您可能想捕获一个某些错误.在这种情况下,请使用catch.这是我文章中的代码:
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.
这篇关于如何检查是否插入失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!