What is the best way to repeat the same query without copying and pasting?

0

I have a query and I need to use it twice, one I'm going to use fetchCollum and another I'm going to use fetch(PDO::FETCH_ASSOC) . That said, I can not apply a fetch and then apply another fetch , for example:

$tokenHash = $query->fetchColumn(10);
    if($query->rowCount() === 0 || (hash_equals($tokenHash, $tokenGet) === FALSE)):
        echo 'Token Inválido!';
        header( "refresh:10;url=listarDados.php" );
        exit;
    else:
        $row = $query->fetch(PDO::FETCH_ASSOC);

It ends up returning me as boolean false . And to not have to do everything again and simply copy and paste, is there an alternative to repeating the same query just using different fetch's?

    
asked by anonymous 13.06.2017 / 17:26

1 answer

1

The simplest way is to store the query result (in $row ) and use it in several places. fetch() will return all the fields chosen in the query when comparing / manipulate just specify which, as in if $tokenHash was changed by $row['tokenHash'] (check that this is the correct field name)

$row = $query->fetch(PDO::FETCH_ASSOC);

if($query->rowCount() === 0 || (hash_equals($row['tokenHash'], $tokenGet) === FALSE)){
    echo 'Token Inválido!';
    header( "refresh:10;url=listarDados.php" );
    exit;
}   

If you want to use fetchColumn() and have used a prepared query, just call the execute() méotod again and make fetch() , the code looks like this:

$row = $query->fetchColumn(10);
if($query->rowCount() === 0 || (hash_equals($tokenHash, $tokenGet) === FALSE)){
    echo 'Token Inválido!';
    header( "refresh:10;url=listarDados.php" );
    exit;
}else{
    $query->execute();
    $row = $query->fetch(PDO::FETCH_ASSOC);
}
    
13.06.2017 / 17:43