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

Asked

Viewed 69 times

0

I have a query and I will need to use it twice, once I will use the fetchCollum and another I will use the fetch(PDO::FETCH_ASSOC). That said, I can’t 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);

He ends up returning me as boolean false.And to not have to do everything again and simply copy and paste, there is an alternative to repeat the same query only to use different fetch’s?

  • Gives a fetch() and store the return, then take this variable solves? if the query is the same has no problem.

  • What do you mean? I don’t understand???

  • It’s almost reversing the question code. Change the fetchColumn() for fetch() at the beginning of the code. No if in place of passing tokenHash pass something like $row['campo_a_ser_validado'].

1 answer

1

The simplest way is to store the result of the query (in $row) and use it in several places. fetch() will return all the fields chosen in the query when comparing/manipulating just specify which one, as in if $tokenHash was exchanged for $row['tokenHash'] (check if 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 wish to use the fetchColumn() and have used a prepared consultation just call the méotod execute() again and do the fetch(), the code stays that way:

$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);
}
  • So @rray, I thought I’d do it this way, but I’d like to do it the way it’s in the question.

  • Specifically do a fetch Collum and then a fetch Assoc, has as without Ctrl c crtrl v?

  • @user6894456 has yes :P is as it is in my answer. Used the prepare() if yes just call again the execute() and make a fetch() in Else

  • Got it, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.