问题
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?
回答1:
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.
回答2:
Firstly i'll suggest you use
if($inserting->rowCount()==1){
echo 'successful';
} else {
echo 'failed';
}
to find out if it actually inserted.
The else statment is not useless. If your query doesnt insert due to a pdo error, then the catch statement will catch the error. But if it doesnt insert without any pdo errors and number of rows is 0 then the else statement will run
回答3:
Try a different output
If you're trying to work out which block is executing, the simplest idea would be to change what's echoed based on which block you hit.
try {
if (...) {
...
} else {
echo "Failed: Some Message";
}
} catch (Exception $e) {
echo "Failed: Some Other Message";
}
Alternatively, you can put a logger function, or some other debug function.
来源:https://stackoverflow.com/questions/37343185/how-to-check-whether-inserting-fails