title: Check PDO query for result and then reuse the data
body: <p>I am new to PDO, and am in the process of upgrading an application from mysql_query to PDO. This is surely a stupid question - but I hope someone can help me wrap my head around it.</p>
  
  <p>I need to see if a PDO query has any data:
  - if it doesn't, throw an error
  - if it does, retrieve that data</p>
  
  <p>I could do this easily with mysql_num_rows, but that's deprecated as we all know.</p>
  
  <p>The issue is that once I've checked if there is any data, I can no longer retrieve it.</p>
  
  <p>The check runs fine, but then when trying to retrieve the actual result, it's empty. I can of course execute the query again after the check - but I'd rather avoid having to run a query twice.</p>
  
  <pre><code>try
  {
      $result = $pdo2-&gt;prepare("SELECT first_name FROM users WHERE email = :email;");
      $result-&gt;bindValue(':email', $email);
      $result-&gt;execute();
      $data = $result-&gt;fetchAll();
  }
  catch (PDOException $e)
  {
          $error = 'Error fetching user: ' . $e-&gt;getMessage();
          echo $error;
          exit();
  }
  
  if (!$data) {
      echo "No data!";
  } else {
      echo "Data found!";
  }           
  
  $row = $result-&gt;fetch();
      echo "First name: " . $row['first_name'];
  </code></pre>
  
  <p>How can I solve this?
  I tried to assign $result to another variable ($test = $result), and then run the data check on the $test variable instead - but even so, the $result variable STILL doesn't return any data after running the check (see the commented lines):</p>
  
  <pre><code>try
  {
      $result = $pdo2-&gt;prepare("SELECT first_name FROM users WHERE email = :email;");
      $result-&gt;bindValue(':email', $email);
      $result-&gt;execute();
      $test = $result; // Duplicating the variable
      $data = $test-&gt;fetchAll(); // Running the check on the duplicated variable
  }
  catch (PDOException $e)
  {
          $error = 'Error fetching user: ' . $e-&gt;getMessage();
          echo $error;
          exit();
  }
  
  if (!$data) {
      echo "No data!";
  } else {
      echo "Data found!";
  }           
  
  $row = $result-&gt;fetch(); // Still doesn't return the result!
      echo "First name: " . $row['first_name'];
  </code></pre>
  
  <p>This is really doing my head in... I think there's a simple solution somewhere, I just can't see it. Please help!</p>