EDIT:
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.
=-=-=-=-=-=-=-=-
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.
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?
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?
I'm open to any feedback on the function, too.
function pdo_query($sql,$data)
{
$stmt = $dbh->prepare($sql);
$first_row = true;
if(is_array($data)){
foreach($data as $row){
if(is_array($row)){
foreach($row as $param => $value){
if($first_row){
//http://bugs.php.net/43130 parameters can't have dashes
$stmt->bindParam($param, ${substr(str_replace('-','_',$param),1)});
}
${substr(str_replace('-','_',$param),1)} = $value;
}
$stmt->execute();
$first_row = false;
}
}
while ($row = $stmt->fetch()) {
$return[] = $row;
}
}
return $return;
}
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:
if ($rows = $stmt->fetchAll()) {
return $rows;
} else if (some_way_of_determining_if_an_insert_happened) {
return $dbh->lastInsertId();
} else {
return some_way_of_returning_affected_rows
}
}