PDO in PHP, how to improve this PDO mysql code
mysql, pdo, php, refactoring
Solution
$myval = "somevalue";
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
//no record matches
//BLOCK A CODE HERE
} else if ($myval == $row['val']) {
//myval is the same as db
//BLOCK B CODE HERE
} else {
//myval is different from db
//BLOCK C CODE HERE
}
Problem
Thanks for checking. All helpful answers/comments are up voted. I have the following code, which does the job, but imo is not efficient. The reason I think it's not efficient is because I'm using fetchAll + loop even though I know that the query will return either 1 or no records. ``` //assume the usual new PDO, binding, and execute are up here $myval = "somevalue"; $res = $stmt->fetchAll(PDO::FETCH_ASSOC); if (!$res) { //no record matches //BLOCK A CODE HERE } else { //found matching record (but always going to be 1 record, no more) foreach($res as $row) { if ($myval == $row['val']){ //myval is the same as db //BLOCK B CODE HERE } else { //myval is different from db //BLOCK C CODE HERE } }//foreach } ``` How can I improve it to remove the bulky look of the foreach and fetchAll (considering I know it's always going to be 1 or 0 record only)? But I still need similar checkpoints so I can execute the same `BLOCK A` `BLOCK B` `BLOCK C` as my current logic needs it.