PDO in PHP how to improve this mysql PDO code

Thanks for checking out. All helpful answers / comments voted. I have the following code that does this work, but imo is inefficient. The reason I think this is inefficient is because I use fetchAll + loop , although 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 cumbersome look of foreach and fetchAll (given that I know it will always be 1 or 0 entries)? But I still need similar breakpoints, so I can do the same BLOCK A BLOCK B BLOCK Cas my current logic requires.

+3
source share
5
$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
}
+6

:

$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
$first_row = ( count($res) ? $res[0] : null );
if ( is_null($first_row) ) {
    // nothing found code
}
else {
    // we found something
    if ($myval == $first_row['val']) {
         // result is good
    }
    else {
         // result is bad
    }
}

PDO :

$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

PDO. try/catch . - :

try {
    // main script logic
}
catch (PDOException $e) {
    // sql error appeared somewhere, we should save it for futher investigation
}
+3

, fetch fetchAll.

+1

SQL :

SELECT * FROM someTable WHERE specificVal = ?

, ->fetch ->fetchAll, ->bindParam. ->prepare ANY $myVa l, , . ?, .

:

$stmt->prepare($yourQuery);
$stmt->bindParam($one,$two);

if($stmt->fetch(PDO::FETCH_ASSOC))
{
// here you can access $two (the result)
}
elseif(empty($two) || !checkForOtherComparisons($two))
{
// here you go if $two is not available or does not match to any other logic
}
+1

Try:

$stmt->fetch( PDO::FETCH_ASSOC );

This will retrieve only the first row.

Since you know for sure that it will only return 1 or 0 rows, it's probably safe to use.

+1
source

Source: https://habr.com/ru/post/1720202/


All Articles