php - Check if PDO executed query has results to fetch -
i have object run database queries , in object have method called runquery() called type of query.
this illustration code:
public function runquery($query){ $stmt->prepare($query); $stmt->execute(); return $stmt->fetchall(); } my problem when run $stmt->errorcode(); see if went fine receive error code: hy000
after search discovered error triggered everytime fetchall() on queries have nothing fetch insert into, update or delete.
my question is, how can verify if executed query has content fetch or not without exploding query see if first word not 1 of three?
you returning wrong value function.
it happens learners overcomplicate code, because know no right way, simple , powerful. , make more complicated, asking question how resolve problem caused initially wrong overcomplicated approach. can resolved in simple way:
you have return statement, not rows. make our function extremely handy , way more useful yet kept simple "illustration code". , solve problem side effect.
public function runquery($query, $data = array()){ $stmt->prepare($query); $stmt->execute($data); return $stmt; } is all code need
want rows @ once? call function way
$obj->runquery($sql)->fetchall(); as can see, in such case fetch method can "linked" runquery() method call, neat oop syntax feature called "method chaining". need return statement, not result.
not writing, enormous flexibility. can any result type want.
in fact, you're limiting 1 result set type, making complicated type. pdo has billions of result set types - need use them.
say, need user name. function? hassle nested arrays? this
$name = $obj->runquery("select name users id=?",[$id])->fetchcolumn(); look, pdo have handy method you. single row?
$user = $obj->runquery("select * users email=?",[$email])->fetch(); or, if want column, not nested simple one-dimensional array? again pdo has method you:
$ids = $obj->runquery("select id news date=?",[$date])->fetchall(pdo::fetch_column); and there other wonderful modes, described in article, the proper guide on pdo. gonna dump them all? really?
or, take initial problem dml query. if want number of affected rows? voila -
$inserted = $obj->runquery($insertquery,$insertdata)->rowcount(); look - need return statement , use method chaining result in desired form.
as bonus, don't need rewrite existing code using inner fetchall() call. if looping on returned result using foreach - still can use same code, using returned statement same:
$data = $obj->runquery($sql); foreach($data $row) ... -- try it, works!
Comments
Post a Comment