Reputation: 1715
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
}
}
Upvotes: 1
Views: 5130
Reputation: 157863
Don't feel too smart.
Make a set of methods.
query
, that returns a resource type.Also a method to produce SET statement would be useful for use with insert and update methods. See this one for the example
Examples:
//SELECT helpers:
$username = $db->getOne("SELECT name FROM users WHERE id=?",$id); //getting scalar
$userinfo = $db->getRow("SELECT * FROM users WHERE id=?",$id); //getting row
$newsdata = $db->getAll("SELECT * FROM news LIMIT ?,?",$start,$rows); //getting array
//Select for mass emailing
$res = $db->query("SELECT * FROM notify WHERE topic_id = ?",$topic);
$num = $db->numRows($res);
while ($row = $db->next()){
mail(...);
}
//insert
$res = $db->query("INSERT INTO users SET name = ?",$name);
$id = $db->lastId();
//delete
$res = $db->query("DELETE FROM users WHERE id = ?",$id);
$rows = $db->affectedRows();
However, I am not sure about affectedRows() and lastId methods, as them takes link identifier as a parameter, not resource identifier....
Upvotes: 2