title: PHP PDO query function
body: <p>EDIT:</p>
  
  <p>I'm marking the answer below correct because of our conversation below. Feel free to post an answer to the unanswered parts and I'll be sure to check back here. Thanks.</p>
  
  <p>=-=-=-=-=-=-=-=-</p>
  
  <p>I'm trying to have one function handle all prepared statements. In my older code, I was mysql_fetch_assoc-ing through select queries. I'd like to just return an array if I'm doing a select and maybe lastInsertId or affectedRows or something if I'm doing an Insert Update or Delete.</p>
  
  <p>My question is, aside from parsing the sql for 'select' or 'insert' or adding another parameter to the function like $type = 'Select' is there something in the PDO class that lets you know if there's data?</p>
  
  <p>I saw somewhere that you can test if the value returned by fetch or fetchAll is true. Is that what I'm supposed to do?</p>
  
  <p>I'm open to any feedback on the function, too.</p>
  
  <pre><code>function pdo_query($sql,$data)
  {
  $stmt = $dbh-&gt;prepare($sql);
  $first_row = true;
  
  if(is_array($data)){
      foreach($data as $row){
          if(is_array($row)){
              foreach($row as $param =&gt; $value){
                  if($first_row){
                      //http://bugs.php.net/43130 parameters can't have dashes
                      $stmt-&gt;bindParam($param, ${substr(str_replace('-','_',$param),1)});
                  }
                  ${substr(str_replace('-','_',$param),1)} = $value;
              }
              $stmt-&gt;execute();
              $first_row = false;
          }
      }
      while ($row = $stmt-&gt;fetch()) {
          $return[] = $row;
      }
  }
  return $return;
  }
  </code></pre>
  
  <p>Edit:
  I haven't tried this yet, but is there any problem testing for $stmnt->fetch()? Also, if I did want to automate getting lastInsertId() or affected rows, it doesn't seem like I can figure out what type of query I'm doing after the fact. Here's where I'm at:</p>
  
  <pre><code>if ($rows = $stmt-&gt;fetchAll()) {
          return $rows;
      } else if (some_way_of_determining_if_an_insert_happened) {
          return $dbh-&gt;lastInsertId();
      } else {
          return some_way_of_returning_affected_rows
      }
  }
  </code></pre>